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?
*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
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;
Are you sure decltype(*this)
is A ? You should investigate on that with an ugly cout
debug line.