Template function is_same in template classes

2019-06-22 05:15发布

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?

3条回答
Rolldiameter
2楼-- · 2019-06-22 05:28

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

查看更多
对你真心纯属浪费
3楼-- · 2019-06-22 05:34

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;
查看更多
混吃等死
4楼-- · 2019-06-22 05:38

*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
查看更多
登录 后发表回答