【问题标题】:Template constructor definition inside a template class definition模板类定义中的模板构造函数定义
【发布时间】:2019-01-05 13:46:17
【问题描述】:

我正在尝试制作一个生成器类,它包含生成的类,两者都扩展了相同的类型。 (在我的程序中,它试图使虚拟化的通用思想)如下:

template <class T>
class V : public T {
    T& owner; // the T owner

    template <class... Args>
    explicit V(T &_owner, Args... args) : T(args...) {
        owner = _owner; // holds the owner
    }
}
...
int main() {
    type t = type(512);
    V<type> vt = V(t, 256); //ERROR: undefinied reference...(to constructor expanded)
}

但是在函数 main 中调用构造函数时出现错误,我需要更改什么?我在 CLion IDE 中使用 C++17。

感谢您的帮助

【问题讨论】:

  • 请在此处按要求发布minimal reproducible example
  • 你试图用T(args...); 做的是创建一个T 类型的临时对象。了解构造函数初始化列表
  • 您还需要对T 的完整定义尝试使用它之前(例如在初始化列表中)。
  • 现在,我尝试如下: V::V(T &_owner, Args... args) : T(args...) { owner = _owner;在构造函数定义中,但仍然有同样的错误。 ://

标签: c++ class templates constructor


【解决方案1】:

以下是对您的代码的一些修复:

template <class T>
class V : public T {
// needs to be public
public:
    T& owner;

    template <class... Args>
    explicit V(T &_owner, Args... args)
        : T(args...),
        // references need to be initialized here
        owner(_owner)
    { }
};

/// the super class
struct memory
{
    memory(int _i) : i(_i) {}
    int i;
};

int main() {
    memory m = memory(512);
    auto vm = V<memory>(m, 256);

    return 0;
}

【讨论】:

    【解决方案2】:

    您的代码中的一个错误是您的class'sconstructor。当您尝试 instantiate class template 中的 main() 对象时,您的 class's constructorprivate。它必须是public

    另一个是当你从constructor'sparameter分配你的class'smember reference时;您不应该在 constructor's 正文中使用 assignment operator,而应该使用 constructor's initializer list

    【讨论】:

      猜你喜欢
      • 2012-08-14
      • 2020-08-08
      • 1970-01-01
      • 2022-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 2012-02-03
      相关资源
      最近更新 更多