C++ remove_pointer und const correctness

Gast #6318250
Lesenswert?

Warum entfernt der folgende Code nicht nur den Pointer sondern auch das 
const?
1
# include <iostream>
2
using std :: cout;
3
using std :: endl;
4
# include <typeinfo>
5
# if 201103L <= __cplusplus
6
#  include <type_traits>
7
using std :: remove_pointer;
8
# else
9
template <typename T>
10
struct remove_pointer {
11
        typedef T type;
12
};
13
template <typename T>
14
struct remove_pointer <T*>{
15
        typedef T type;
16
};
17
# endif
18
int main () {
19
        cout << typeid (int) . name () << endl;
20
        cout << typeid (int*) . name () << endl;
21
        cout << typeid (int const*) . name () << endl;
22
        cout << typeid (remove_pointer <int> :: type) . name () << endl;
23
        cout << typeid (remove_pointer <int*> :: type) . name () << endl;
24
        cout << typeid (remove_pointer <int const*> :: type) . name () << endl;
25
}
1
% g++ -std=c++98 -pedantic -otest test.cpp
2
% c++filt -t `./test`
3
int
4
int*
5
int const*
6
int
7
int
8
int
1
% g++ -std=c++20 -pedantic -otest test.cpp
2
% c++filt -t `./test`                     
3
int
4
int*
5
int const*
6
int
7
int
8
int
Gast #6318272
Lesenswert?

Rolf M. schrieb:
> Er entfernt es nicht, sondern das const ist einfach nicht Teil der
> typeid.

Danke, das wusste ich noch gar nicht, dass sich Typeid und Traits da 
unterscheiden.

[code]
$ cat test.cxx
# include <iostream>
using std :: cout;
using std :: endl;
# include <typeinfo>
# include <type_traits>
using std :: is_same;
int main () {
        cout << is_same <int, int const> :: value << endl;
        cout << (typeid (int) == typeid (int const)) << endl;
}
$ c++ test.cxx && ./a.out
0
1
[code]
Gast #6318286
Lesenswert?

Falls du es noch nicht kennst, solltest du dir _PRETTY_FUNCTION_ 
angucken.
Dieses "Makro" ist sehr hilfreich, im beim Loggen von Debuginfos und 
generell beim Umgang mit Templates. Vor allem das folgende Beispiel ist 
sehr hiflreich, wenn man mal keine Lust hat über type deduction 
nachzudenken:
1
#include <iostream>
2
#include <type_traits>
3

4
template<typename T>
5
void foo() {
6
    std::cout << __PRETTY_FUNCTION__ << std::endl;
7
}
8

9
int main () {
10
        foo<int>();
11
        foo<int*>();
12
        foo<int const*>();
13
        foo<std::remove_pointer<int>::type>();
14
        foo<std::remove_pointer<int*>::type>();
15
        foo<std::remove_pointer<int const*>::type>();
16
}

liefert
1
void foo() [T = int]
2
void foo() [T = int *]
3
void foo() [T = const int *]
4
void foo() [T = int]
5
void foo() [T = int]
6
void foo() [T = const int]

Mindestens gcc und clang kennen _PRETTY_FUNCTION_.

Antwort schreiben

Bitte melde dich an, um einen Beitrag zu schreiben.

oder

Mit Google-Account einloggen

Die Registrierung ist kostenlos und dauert nur eine Minute.

Jetzt registrieren