給定型別別的指標型別作為模板引數,有沒有辦法呼叫類的建構式?
MyClass<AnotherClass*> => how to call the default constructor of AnotherClass in MyClass?
這顯然不起作用(不編譯),因為在GetNew和new T回傳型別 T 不適合在一起。在給定指標型別的情況下,需要某種“型別解除參考”來處理型別別。
class AnotherClass
{};
template <class T>
class MyClass
{
public:
// this does obviously not compile
virtual T GetNew()
{
return new T; // how let T be AnotherClass* and to create an AnotherClass instance here?
}
};
int main()
{
// this does not compile:
MyClass<AnotherClass*> tmp; // here, AnotherClass is **pointer** type
AnotherClass* a = tmp.GetNew();
}
一種解決方法是使用型別別作為模板引數并使用指標型別作為回傳型別。但這改變了界面,所以我仍然想要指標模板型別的解決方案。
class AnotherClass
{};
template <class T>
class MyClass2
{
public:
virtual T* GetNew()
{
return new T;
}
};
int main()
{
// this does work:
MyClass2<AnotherClass> tmp2; // here, AnotherClass is **not** pointer type
AnotherClass* b = tmp2.GetNew();
}
另一種解決方法可能是使用工廠或類似方法,但我想使用默認建構式而不需要額外的幫助結構。
uj5u.com熱心網友回復:
您可以使用std::remove_pointer來獲取指向的型別。
提供成員 typedef type,它是 T 所指向的型別,或者,如果 T 不是指標,則 type 與 T 相同。
例如
virtual T GetNew()
{
return new std::remove_pointer_t<T>;
}
uj5u.com熱心網友回復:
如果您要求引數MyClass是指標,則可以將其專門用于指標,而將其未定義以用于其他型別
template<typename>
class MyClass;
template<typename T>
class MyClass<T*>
{
public:
virtual T* GetNew()
{
return new T;
}
};
int main()
{
// MyClass2<AnotherClass> tmp1; // compile error
MyClass2<AnotherClass *> tmp2; // fine
AnotherClass* b = tmp2.GetNew(); // GetNew returns the exact type parameter
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/518282.html
標籤:C 模板
上一篇:遞回模板實體化因元組而失敗
下一篇:在型別樹中找到最近的“祖先”
