Search code examples
c++14decltypetypename

Why isn't typename interchangeable with decltype() for this usage?


For a given usage

template<typename T1> 
class node{

public:
using sp2node = shared_ptr<node<T1>>;
using r_sp2node = shared_ptr<node<T1>>&;

public:
r_sp2Node getN();

private:
sp2node N;

};

(1)

template<typename T1> decltype(node<T1>::r_sp2node) node<T1>::getN(){

       return N;

}

(2)

template<typename T1> typename node<T1>::r_sp2node node<T1>::getN(){

       return N;

}

(1) generates the compiler error:

error: missing 'typename' prior to dependent type name 
    'node<T1>::r_sp2node'

whereas (2) compiles

Can someonene explain what is the difference between the above two?


Solution

  • There are two things wrong with the first example.

    • In decltype(node<T1>::r_sp2node), reading inside out, the compiler first needs to know what node<T1>::r_sp2node. Is it a type, or something else? This is why the typename disambiguator exists, and that is what the error message is all about.
    • The second problem is that decltype expects some expression, not a type. So even if you used typename, it still wouldn't compile. (As a simple example, decltype(int) won't even compile.)

    To answer the question specifically, the difference between the two is that the first is not valid C++ and the second is the way to go.