Template function is_same in template classes

一世执手 提交于 2019-12-12 11:02:29

问题


Why this code produces a false output?

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

Output:

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

The type of "*this" inside A through B is A< int >, isn't it?


回答1:


*this is an lvalue of type A, so decltype(*this) will give the reference type A &. Recall that decltype on an lvalue gives the reference type:

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

Output:

false
true



回答2:


Try:

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

and maybe remove_cv in some other contexts (if you don't care about const/volatile) like this:

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;



回答3:


Are you sure decltype(*this) is A ? You should investigate on that with an ugly cout debug line.



来源:https://stackoverflow.com/questions/13843222/template-function-is-same-in-template-classes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!