Related question: template-function-is-same-in-template-classes
I’m a bit disconcerted with the type of the pointer “this” (gcc 4.7.2, c++11). In principle, the type of pointer “this” of a non-const object of type C, for example, is “C * const”, and thus, the type of “*this” is “C”. But the behaviour of the “is_same” class confused me.
Test:
// 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();
}
Output:
$ 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
However, the expected output is:
$./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*
What are happened here?
In this case, the type of
thisisC *No mention for
X *const, etc. Thethispointer is a prvalue, that’s why it cannot be assigned to, not because it const-qualified.PS. By the way, it seems
though it may be an artefact of the implementation (compiler or
is_same), because the standard says: