5

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 Answers 3

8

*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
5
  • Then, the complete type of 'this' what is, 'A<int>&* this'?
    – ABu
    Dec 12, 2012 at 15:52
  • Definitely not obvious though. Dec 12, 2012 at 15:52
  • The last line doesn't work for me. My output is 'false', 'true', 'false' (g++ (Ubuntu/Linaro 4.7.2-2ubuntu1) 4.7.2)
    – ABu
    Dec 12, 2012 at 15:58
  • @Peregring-lk this is a prvalue expression of type A<int> *. Indirecting this gives an lvalue expression of type A<int>. The type of an expression isn't always the same as how decltype reports it.
    – ecatmur
    Dec 12, 2012 at 15:59
  • @Peregring-lk oops, my mistake on the parenthesis bit. Corrected.
    – ecatmur
    Dec 12, 2012 at 16:02
2

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;
5
  • 2
    And make sure remove_cv is after remove_reference. Dec 12, 2012 at 15:48
  • @R.MartinhoFernandes remove_reference has colateral effects? Why is it neccesary to use remove_cv "after" remove_reference?
    – ABu
    Dec 12, 2012 at 16:11
  • @Peregring-lk because the order matters. See here flamingdangerzone.com/cxx11/2012/05/29/… Dec 12, 2012 at 16:16
  • @Peregring-lk basically because a int&const doesn't exist, yet is distinct from a int const&. remove_cv removes the const-volatile from the "outermost layer" of the type, so would turn int*const into a int*, but would leave a int const& or int const* untouched. Dec 12, 2012 at 16:18
  • Yes, there was a typo up there for a short bit. Sorry! Dec 12, 2012 at 16:29
0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.