2012-12-12 19 views
5

Perché questo codice produce un'uscita falsa?Funzione template is_same nelle classi template

//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; 
} 

uscita:

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

Il tipo di "* questo" dentro da A a B è un < int>, non è vero?

risposta

8

*this è un lvalue di tipo A, quindi decltype(*this) darà il tipo di riferimento A &. Ricordiamo che decltype su un lvalue dà il tipo di riferimento:

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

uscita:

false 
true 
+0

Poi, il tipo completo di 'questo' che cos'è, 'A e * questo'? –

+0

Sicuramente non ovvio. –

+0

L'ultima riga non funziona per me. Il mio output è 'false', 'true', 'false' (g ++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2) –

0

Sei sicuro decltype(*this) è A? Dovresti indagare su questo con una brutta riga di debug cout.

2

Prova:

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

e magari remove_cv in alcuni altri contesti (se non si cura di const/volatile) come questo:

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

E assicurati che remove_cv sia * dopo * remove_reference. –

+0

@ R.MartinhoFernandes remove_reference ha effetti collaterali? Perché è necessario usare remove_cv "dopo" remove_reference? –

+0

@ Peregring-lk perché l'ordine è importante. Vedi qui http://flamingdangerzone.com/cxx11/2012/05/29/type-traits-galore.html#bare_types –

Problemi correlati