对于这种用法,为什么 typename 不能与 decltype() 互换?

Why isn't typename interchangeable with decltype() for this 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) 生成编译器错误:

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

而 (2) 编译

有人能解释一下以上两者有什么区别吗?

第一个例子有两处错误。

  • decltype(node<T1>::r_sp2node)中,从里到外读,编译器首先需要知道node<T1>::r_sp2node是什么。它是一种类型,还是其他什么?这就是 typename 消歧器存在的原因,这就是错误消息的全部内容。
  • 第二个问题是decltype需要一些表达式,而不是类型。所以即使你使用 typename,它仍然无法编译。 (作为一个简单的例子,decltype(int) 甚至不会编译。)

具体回答问题,两者的区别在于第一个不是有效的C++,第二个是要走的路。