2012-12-12 18 views
5

Dlaczego ten kod generuje fałszywe dane wyjściowe?Funkcja szablonu is_same w klasach szablonów

//this-type.cpp 

#include <iostream> 
#include <type_traits> 

using namespace std; 

template<typename testype> 
class A 
{ 
public: 
    A() 
    { 
     cout << boolalpha; 
     cout << is_same<decltype(*this), A<int>>::value << endl; 
    } 
}; 

class B : public A<int> 
{ 
}; 

int main() 
{ 
    B b; 
} 

wyjściowa:

$ g++ -std=c++11 this-type.cpp 
$ ./a.out 
false 

Typ "* to" wewnątrz A do B jest < int>, prawda?

Odpowiedz

8

*this jest lwartością typu A, więc decltype(*this) poda typ odniesienia A &. Przypomnijmy, że decltype na lwartością daje typ referencyjny:

cout << is_same<decltype(*this), A<int>>::value << endl; 
    cout << is_same<decltype(*this), A<int> &>::value << endl; 

wyjściowa:

false 
true 
+0

Następnie kompletna typ 'to' co to jest "A & * to"? –

+0

Zdecydowanie nie jest to oczywiste. –

+0

Ostatnia linia nie działa dla mnie. Moje wyniki to "false", "true", "false" (g ++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2) –

0

Czy na pewno decltype(*this) jest A? Powinieneś to sprawdzić za pomocą brzydkiej linii debugowania cout.

2

Spróbuj:

typedef std::remove_reference<decltype(*this)>::type this_type; 
cout << is_same<this_type, A<int>>::value << endl; 

a może remove_cv w niektórych innych kontekstach (jeśli nie dbają o const/volatile) tak:

typedef std::remove_reference<decltype(*this)>::type this_type; 
typedef std::remove_cv<this_type>::type no_cv_this_type; 
cout << is_same<no_cv_this_type, A<int>>::value << endl; 
+2

Upewnij się, że remove_cv jest * po * remove_reference. –

+0

@ R.MartinhoFernandes remove_reference ma efekty boczne? Dlaczego konieczne jest użycie remove_cv "after" remove_reference? –

+0

@ Peregring-lk, ponieważ kolejność ma znaczenie. Zobacz tutaj http://flamingdangerzone.com/cxx11/2012/05/29/type-traits-galore.html#bare_types –

Powiązane problemy