[英]Template constructor definition inside a template class definition
我試圖像一個生成器類一樣保存生成的類,兩者都擴展了相同的類型。 (在我的程序中它試圖使虛擬化的通用思想)如下:
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。
謝謝您的幫助
以下是對您的代碼的一些修復:
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;
}
代碼中的錯誤之一是class's
constructor
。 當您嘗試在main()
instantiate
class template
對象時,您的class's
constructor
是private
。 它需要public
。
另一個是當您從constructor's
parameter
分配class's
member reference
; 您不應該在constructor's
體內使用assignment operator
,而應該使用constructor's
initializer list
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.