相关问题:模板功能在模板类中相同
我对指针“this”(gcc 4.7.2,c++11)的类型有点不安。原则上,例如C类型的非常量对象的指针“this”的类型是“C * const”,因此“*this”的类型是“C”。但是“is_same”类的行为让我很困惑。
测试:
// this-type.cpp
#include <iostream>
#include <type_traits>
using namespace std;
class C
{
public:
void test()
{
cout << boolalpha;
cout << "'this' const?" << " "
<< is_const<decltype(this)>::value << endl;
cout << "'*this' const?" << " "
<< is_const<decltype(*this)>::value << endl;
cout << "'*this' and 'C' the same?" << " "
<< is_same<decltype(*this), C>::value << endl;
cout << "'this' and 'C*' the same?" << " "
<< is_same<decltype(this), C*>::value << endl;
}
};
int main()
{
C c;
c.test();
}
输出:
$ g++ --version | grep g++
g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2
$ g++ -std=c++11 this-type.cpp
$ ./a.out
'this' const? false
'*this' const? false
'*this' and 'C' the same? false
'this' and 'C*' the same? true
但是,预期的输出是:
$./a.out
'this' const? true // C* const
'*this' const? false // C
'*this' and 'C' the same? true
'this' and 'C*' the same? false // C* const vs. C*
这里发生了什么?