2012-12-12 25 views
5

Bu kod neden yanlış bir çıktı üretir?Şablon işlevi, şablon sınıflarında is_same

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

Çıktı:

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

tipi "* Bu" B aracılığıyla A A < int> olan iç, öyle değil mi?

cevap

8

*this, A türünde bir değerdir, bu nedenle decltype(*this), A & başvuru türünü verecektir.

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

Çıktı:

false 
true 
+0

, 'bu' tam tip 'A & * bu' nedir? –

+0

Yine de belli değil. –

+0

Son satır benim için çalışmıyor. Çıktım 'false', 'true', 'false' (g ++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2) –

0

Eğer decltype(*this) emin A'nın lvalue üzerinde decltype referans tipini verdiğini hatırlayın? Bunun üzerinde çirkin bir cout hata ayıklama çizgisi ile araştırmalısınız.

2

Dene:

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

ve diğer bazı bağlamlarda belki remove_cv böyle (eğer umursamazsak yaklaşık const/volatile): Sonra

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

Ve remove_cv'nin * remove_reference öğesinden sonra * olduğundan emin olun. –

+0

@ R.MartinhoFernandes remove_reference'in yan etkileri var mı? Neden remove_rev "after" remove_reference kullanmak için gereksizdir? –

+0

@ Peregring-lk, çünkü sipariş önemlidir. Http://flamingdangerzone.com/cxx11/2012/05/29/type-traits-galore.html#bare_types –

İlgili konular