【问题标题】:How to get typename defined in derived from base class?如何获取从基类派生的类型名?
【发布时间】:2017-12-02 10:02:37
【问题描述】:
template <class Derived>
struct Base {
  typedef typename Derived::T T;
};

template <typename T_>
struct Impl : public Base<Impl<T_>> {
  typedef T_ T;
};

当初始化这个时,我得到一个错误

“Impl”中没有名为“T”的类型

那么,我怎样才能得到从基类派生的类型名呢?

【问题讨论】:

  • 这不是关于 `typename' 关键字本身,而是关于 typename 的可见性。
  • 我会说这是一种循环定义,你在 Impl 中定义了两次 T,你的意思是 struct Impl : public Base&lt;T_&gt; {
  • @nsubiron 您可以将第一个 typedef 更改为 typedef typename Derived::T T2;。不会真正影响错误。
  • 没错,问题不在于重名。我的猜测是,在生成 Base 模板时,您还不了解 Impl 的内部。编译器首先需要生成 Base 类才能创建 Impl,所以此时 Impl 还没有 T 类型

标签: c++ typedef crtp


【解决方案1】:

找到一种方法来做到这一点,虽然它并不完美但确实有效。

template <class T>
struct traits;

template <class Derived>
struct Base {
  typedef typename traits<Derived>::T T;
};

template <typename T_>
struct Impl : public Base<Impl<T_>> {
  typedef T_ T;
};

template <typename T_>
struct traits<Impl<T_>> {
  typedef T_ T;
};

这并不完美,因为在特质类中,我不会写

typedef typename Impl<T_>::T T;

它仍然是未定义的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-09
    • 2015-03-30
    • 2010-11-25
    • 2010-11-01
    • 1970-01-01
    • 2011-03-05
    • 2018-11-19
    • 2016-02-23
    相关资源
    最近更新 更多