为什么类不能从 decltype 的结果继承?

Why can't a class inherit from the result of a decltype?

本文关键字:结果 继承 decltype 不能 为什么      更新时间:2023-10-16

为什么一个类在继承列表中不能有decltype?例如,我希望以下代码使A<B>RType继承,但对于G++4.6.1(使用-std=c++0x),它不编译:

#include <type_traits>
template<typename T>
class A : public decltype(std::declval<T>().hello()) { };
class RType { };
class B {
public:
    RType hello() { return RType(); }
};
int main() {
    A<B> a;
}

它给出以下输出:

test.cpp:6:18: error: expected class-name before 'decltype'
test.cpp:6:18: error: expected '{' before 'decltype'
test.cpp:6:54: error: expected unqualified-id before '{' token
test.cpp: In function 'int main()':
test.cpp:16:7: error: aggregate 'A<B> a' has incomplete type and cannot be defined

declval的使用只是为了提供一个需要使用decltype的实例,但decltype的其他使用也会失败(即没有declval)。

允许:

10.1:"基类列表可以在类定义中使用以下符号指定:"

class-or-decltype:
nested-name-specifieropt class-name
decltype-specifier

所以我猜你的编译器有错误

它看起来像GCC中的一个bug。试试4.7。

解决方法:

template <typename T>
class ID
{
 public:
  typedef T type;
};
template<typename T>
class A : public ID<whatever>::type { };

您可以尝试类似的方法

template<typename T>
class A : public result_of<T::hello()>

尽管它可能期望该语法有一个静态成员函数,而且它可能会遇到阻止decltype工作的同一个错误。