Pet*_*lev 5 c++ templates compiler-errors c++11
我正在尝试创建一个可以使用特定数据类型的类,并且我希望在不支持数据类型时出现编译时错误.
我试图专门化这样的模板.
template<>
float Foo::get<float>(const std::string& key)
{
return std::stof(key);
}
Run Code Online (Sandbox Code Playgroud)
并std::static_assert在通用函数中添加一个因为我只需要指定的这些类型.
template<class T>
T Foo::get(const std::string&)
{
static_assert(false, "unsupported data type");
return T(0);
}
Run Code Online (Sandbox Code Playgroud)
不幸的是我得到了编译错误(静态断言失败),即使我有这种类型的专用函数.
我找到了一种方法只为特定类型做这件事,但它看起来有点愚蠢而且不通用.
T Foo::get(const std::string&)
{
static_assert(
std::is_same<T,float>::value ||
std::is_same<T,double>::value ||
std::is_same<T,bool>::value ||
std::is_same<T,uint32_t>::value ||
std::is_same<T,int32_t>::value ||
std::is_same<T,std::string>::value,
"unsuported data type");
return T(0);
}
Run Code Online (Sandbox Code Playgroud)
您可以static_assert根据模板参数进行设置T,然后直到实例化时(即将确切类型作为模板参数进行探索时)才会对其进行求值。例如
template<class T>
T get(const std::string&)
{
static_assert(!std::is_same<T, T>::value, "unsupported data type");
return T(0);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
548 次 |
| 最近记录: |