[英]C++: how to get the type of a variable and use this as a template
我正在為以這種方式聲明的函數的C ++編寫一個包裝器:
class MyClass
{
public:
template <class T>
T& as();
};
我的包裝器需要消除顯式模板,因為我不想調用myClass.as<int>();
所以我嘗試實現以這種方式聲明的新函數:
class MyClass2 : public MyClass
{
public:
template <class T>
void get(T & val);
};
通過這種方式我可以打電話
int a;
myClass2.get(a);
有沒有辦法實現這個函數,所以類型是在運行時根據參數類型傳遞的? 就像是:
template <class T>
void MyClass2::get(T & val)
{
val = as< typeof(val) >(); /* Of course typeof does not exist */
}
非常感謝您的幫助。
這根本不符合邏輯。 為什么不寫:
template <class T>
void MyClass2::get(T & val)
{
val = as< T >();
}
由於type是模板參數,因此不需要typeof
。
正如@ Space_C0wb0y已經指出的那樣,這實際上並不是必需的。 從參數自動推斷模板類型。
但是,C ++ 0x 確實添加了你要求的內容,因為它可以讓你寫:
template <class T>
void MyClass2::get(T & val)
{
val = as< decltype(val) >(); /* typeof does not exist. But decltype does */
}
當然,在這種情況下,它只是一種解決不存在問題的更復雜的方法。 但我認為無論如何我都會展示它,因為它與您在問題中發布的偽代碼非常相似。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.