【发布时间】:2017-12-10 08:56:39
【问题描述】:
我正在尝试创建一个适用于特定数据类型的类,并且我希望在不支持数据类型时出现编译时错误。
我试图专门化这样的模板。
template<>
float Foo::get<float>(const std::string& key)
{
return std::stof(key);
}
并在泛型函数中添加std::static_assert,因为我只需要指定的这些类型。
template<class T>
T Foo::get(const std::string&)
{
static_assert(false, "unsupported data type");
return T(0);
}
不幸的是,我得到了编译错误(静态断言失败),即使我有这个类型的专用函数。
我找到了一种仅针对特定类型的方法,但它看起来有点愚蠢而且不是通用的。
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);
}
【问题讨论】:
-
为此目的有一个花哨的技巧 (
always_false<T>::value),但我认为不定义主模板会更简单。
标签: c++ c++11 templates compiler-errors