Ela*_*oni 3 c++ c++-concepts c++20
我正在尝试使用 C++ 概念来编写一个类型特征,该特征将根据其模板参数是否为基本类型而生成不同的类型:
template<typename T>
concept fundamental = std::is_fundamental_v<T>;
template<typename T>
concept non_fundamental = !std::is_fundamental_v<T>;
Run Code Online (Sandbox Code Playgroud)
以下代码按预期工作:
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"
}
Run Code Online (Sandbox Code Playgroud)
对类型特征应用相同的想法是行不通的。
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
Run Code Online (Sandbox Code Playgroud)
我收到编译器错误 (MSVC),内容如下:
error C3855: 'SomeTypeTrait': template parameter 'T' is incompatible with the declaration
Run Code Online (Sandbox Code Playgroud)
如何使用概念实现所需的行为?
显然语法与我的想法略有不同。
这是一个可行的解决方案:
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>;
};
Run Code Online (Sandbox Code Playgroud)
此外,其中一种专业化可以成为默认实现,以使代码更短,并允许稍后添加更多专业化:
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;
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
437 次 |
最近记录: |