[英]How to specialize a type trait using concepts?
我正在嘗試使用 C++ 概念來編寫一個類型特征,該特征將根據其模板參數是否為基本類型而產生不同的類型:
template<typename T>
concept fundamental = std::is_fundamental_v<T>;
template<typename T>
concept non_fundamental = !std::is_fundamental_v<T>;
以下代碼按預期工作:
void Print(fundamental auto value)
{
std::cout << "fundamental\n";
}
void Print(non_fundamental auto value)
{
std::cout << "non fundamental\n";
}
int main()
{
Print(1); // prints "fundamental"
Print(std::string("str")); // prints "non fundamental"
}
在類型特征上應用相同的想法是行不通的。
template<fundamental T>
struct SomeTypeTrait
{
using type = T;
};
template<non_fundamental T>
struct SomeTypeTrait
{
using type = std::shared_ptr<T>;
};
using ExpectedToBeDouble = SomeTypeTrait<double>::type;
using ExpectedToBeSharedPtrOfString = SomeTypeTrait<std::string>::type; // fails to compile
我收到編譯器錯誤 (MSVC) 說:
error C3855: 'SomeTypeTrait': template parameter 'T' is incompatible with the declaration
如何使用概念實現所需的行為?
顯然語法與我的想法略有不同。
這是一個有效的解決方案:
template<typename T>
struct SomeTypeTrait {};
template<fundamental T>
struct SomeTypeTrait<T> // note the extra <T>
{
using type = T;
};
template<non_fundamental T>
struct SomeTypeTrait<T> // note the extra <T>
{
using type = std::shared_ptr<T>;
};
此外,其中一個專業化可以成為默認實現,使代碼更短一些,並允許以后添加更多專業化:
template<typename T>
struct SomeTypeTrait // default
{
using type = std::shared_ptr<T>;
};
template<fundamental T>
struct SomeTypeTrait<T> // specialization for fundamental types
{
using type = T;
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.