模板类中的模板函数is_same

Per*_*-lk 5 c++ types this c++11

为什么这段代码产生错误输出?

//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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

$ g++ -std=c++11 this-type.cpp
$ ./a.out
false
Run Code Online (Sandbox Code Playgroud)

A到B里面的"*this"的类型是A <int>,不是吗?

eca*_*mur 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;
Run Code Online (Sandbox Code Playgroud)

输出:

false
true
Run Code Online (Sandbox Code Playgroud)