[英]Template specialization with alternative return type
我有一個類模板成員函數,我需要創建一個特殊化,該特殊化取決於返回類型。 但這是不允許的。
template<typename Type>
class Class {
Type Method(Type Argument) {...}
};
template <>
double Class<int>::Method(int Argument) {...}
您可以提出解決方法嗎? (目的是隱藏int
的模板定義。)
讓我們討論問題的根源。 當您為類模板專門化成員函數時,它將導致實例化類的聲明。 因此,您的特殊類外定義與生成的聲明沖突。
一種可能的解決方案是添加一個間接層。 不要按原樣對返回類型進行硬編碼,而是使其間接依賴於模板參數,例如來自traits類。
像這樣:
template<typename T>
struct ClassMethodReturn { typedef T type; };
template<>
struct ClassMethodReturn<int> { typedef double type; };
template<typename Type>
class Class {
typedef typename ClassMethodReturn<Type>::type ret_type;
ret_type Method(Type Argument) { return ret_type(); }
};
template <>
double Class<int>::Method(int Argument) { return 0.0; }
因此,您可以輕松控制每個專業化的返回類型。
這是使用std::enable_if
另一種解決方法。
template<typename Type>
class Class {
public:
template <typename TypeDat=Type> std::enable_if_t<std::is_same<TypeDat,int>::value,double> Method(Type Argument) {
std::cout<<"case 1"<<std::endl;
}
template <typename TypeDat=Type> std::enable_if_t<!std::is_same<TypeDat,int>::value,Type> Method(Type Argument) {
std::cout<<"case 2"<<std::endl;
}
};
int main() {
Class<int> a;
a.Method(5); //print case 1
Class<char> b;
b.Method('c'); //print case 2
}
就個人而言,我喜歡StoryTeller的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.