【问题标题】:Referencing struct definition inside class in CRTP在 CRTP 中的类内引用结构定义
【发布时间】:2013-04-30 06:56:29
【问题描述】:

我正在使用静态多态性(CRTP 方法)来创建类层次结构。这个想法是在基类中使用派生类中定义的结构。但是,VC10 会产生以下错误:

error C2039: 'param_t' : is not a member of 'D'

英特尔 C++ 生成以下错误:

error : incomplete type is not allowed

Derived::param_t 是一个struct 类型并且应该被正常编译,这很令人困惑。请指出代码中的问题。谢谢。

// Base class
template<typename Derived>
struct Base {
  typedef typename Derived::param_t param_t; //error c2039

  void setParam(param_t& param);
  const param_t& getParam() const;
  ...

};

// Derived class
class D: public Base<D> {
public:
  struct param_t {
    double a, b, c;
  };

  D(param_t& param):param_(param) {}
  ...

protected:
  param_t param_;   

};

int main()
{
  D::param_t p = {1.0, 0.2, 0.0};
  D *pD = new D(p);
}

【问题讨论】:

  • 你能在Base中显示所有对param_t的引用吗?
  • 您好,欢迎来到 StackOverflow!请务必阅读FAQ,尤其是在发布问题之前如何研究您的问题。例如。搜索“CRTP 不完整类型”会为您提供大量信息。
  • 很抱歉发布重复的主题。解决方案是 trait 类或模板成员函数 'setParam' 'getParam'。我更喜欢后者,因为出于封装目的,“结构”定义应位于“D 类”内部。感谢所有帮助和建议。

标签: c++ struct crtp incomplete-type


【解决方案1】:

您不能在基类定义中使用派生类的类型。您只能在成员函数体内使用它。问题是,当编译器还不知道 D 的嵌套类型时,typedef typename Derived::param_t param_t 被解析为 class D: public Base&lt;D&gt;。当 D 的定义可用时,在 D 的实际实例化之后编译成员函数。

我认为在你的情况下你不能使用 CRTP 方法。

【讨论】:

  • 我明白了,这是一个循环引用方案。谢谢。
  • 没错。两个类的定义相互依赖。
猜你喜欢
  • 2012-11-07
  • 1970-01-01
  • 2010-10-09
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-02
  • 1970-01-01
相关资源
最近更新 更多