[英]std::enable_if for template method defined in cpp
我在一個模板化的類上工作,它的方法定義在 cpp 文件中。 現在我想添加另一種方法,該方法僅對某些類模板參數啟用。 我目前的做法:
template <typename T>
class MyClass
{
template <typename U = T,
typename std::enable_if<std::is_same<SpecialType, U>::value>::type* = 0>
T& Foo();
}
template <typename T>
template <typename U,
typename std::enable_if<std::is_same<SpecialType, U>::value>::type*>
T& MyClass<T>::Foo()
{
// Implementation...
}
// Exported explicit instantiations
template class __declspec(dllexport) MyClass<SpecialType>;
template class __declspec(dllexport) MyClass<OtherType>;
...
這在實現 cpp 和包含標題的站點中都可以很好地編譯。 問題出在鏈接器上,我得到了未解析的外部符號。
error LNK2019: unresolved external symbol
"public: class SpecialType & __cdecl MyClass<class SpecialType>::Foo<class SpecialType,0>(void)"
(??$Foo@VSpecialType@@$0A@@?$MyClass@VSpecialType@@@@QEAAAEAVSpecialType@@XZ) referenced in function MyFunction
問題是什么? 順便說一句:其他非 enable_if 方法鏈接良好。
您聲明Foo
的方式需要像Foo<>()
一樣調用,這不太理想。
現在我想添加另一種方法,該方法僅對某些類模板參數啟用。
實現這一目標的另一種方法是為SpecialType
專門化類的(派生)部分:
struct SpecialType;
template<typename T>
struct MyClassCommon {};
// Generic version.
template<typename T>
struct MyClass : MyClassCommon<T> {
using MyClassCommon<T>::MyClassCommon;
};
// Specialization for SpecialType.
template<>
struct MyClass<SpecialType> : MyClassCommon<SpecialType> {
using MyClassCommon<SpecialType>::MyClassCommon;
SpecialType& foo();
};
用法是:
MyClass<int> a;
// a.foo(); // error: 'struct MyClass<int>' has no member named 'foo'
MyClass<SpecialType> b;
b.foo();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.