2012-12-12 196 views
5

为什么此代码会产生错误输出?模板类中的模板函数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; 
} 

输出:

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

类型的 “*这种” 内部的通过B是A < int>的,是吗?

回答

8

*this是类型A的左值,因此decltype(*this)将给出参考类型A &。回想一下,decltype上左值给出了引用类型:

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

输出:

false 
true 
+0

然后,完全型的 '本'什么是'A &*这'? –

+0

虽然不是很明显。 –

+0

最后一行对我不起作用。我的输出是'false','true','false'(g ++(Ubuntu/Linaro 4.7.2-2ubuntu1)4.7.2) –

0

确定decltype(*this)是A?你应该用一个丑陋的cout调试线进行调查。

2

尝试:

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

,并在一些其他情况下也许remove_cv(如果你不关心const/volatile)是这样的:

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

并确保remove_cv *在* remove_reference之后*。 –

+0

@ R.MartinhoFernandes remove_reference有副作用吗?为什么在remove_reference之后使用remove_cv“是必须的? –

+0

@ Peregring-lk因为订单很重要。看到这里http://flamingdangerzone.com/cxx11/2012/05/29/type-traits-galore.html#bare_types –