【问题标题】:Why can't a class inherit from the result of a decltype?为什么类不能从 decltype 的结果继承?
【发布时间】:2012-03-11 06:12:44
【问题描述】:

为什么一个类不能在继承列表中有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)。

【问题讨论】:

  • 你试过 gcc 4.7、clang 或任何其他编译器吗? gcc 还不完全符合 C++11...
  • @PlasmaHH 我现在实际上正在尝试编译 clang(出于其他原因),但对于 MSVC++ 2010,它不起作用。

标签: c++ inheritance c++11 decltype


【解决方案1】:

你可以试试

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

虽然它可能需要该语法的静态成员函数,但它可能会遇到阻止 decltype 工作的相同错误。

【讨论】:

    【解决方案2】:

    解决方法:

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

    【讨论】:

    • 请注意,我从作为函数返回类型的类型继承。这不能/不能做同样的事情。
    • @Seth :我认为这意味着尝试template&lt;typename T&gt; class A : public ID&lt;decltype(std::declval&lt;T&gt;().hello())&gt;::type { };
    • 您可以使用std::enable_if&lt;true, decltype(...)&gt;::type,而不是编写自己的课程
    • 我认为身份转换已经足够重要了,应该单独定义并使用其专有名称。
    【解决方案3】:

    这是允许的:

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

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

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

    【讨论】:

    • Eclipse CDT 也将此报告为语法错误,但实际上它可以编译。
    【解决方案4】:

    看起来像a bug in GCC。试试 4.7。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-06
      • 2010-10-20
      • 1970-01-01
      • 2014-09-09
      • 2015-06-20
      • 1970-01-01
      • 2010-09-28
      相关资源
      最近更新 更多