【发布时间】:2019-04-26 00:19:41
【问题描述】:
我有以下模板函数
template <typename As, typename std::enable_if<
std::is_arithmetic<As>::value, As>::type* = nullptr >
As getStringAs(const std::string& arg_name)
{
std::istringstream istr(arg_name);
As val;
istr >> val;
if (istr.fail())
throw std::invalid_argument(arg_name);
return val;
}
我想这样使用它:
getStringAs<float>("2.f");
什么是专门化std::string 的函数以便我可以编写的好方法
getStringAs<std::string>("2.f");
我已经尝试了所有已知的方法,但由于std::enable_if 的默认类型产生的歧义,它们似乎都失败了。
例如:如果我写:
template<>
std::string getStringAs<std::string>(const std::string& arg_name)
{
}
这将不匹配任何模板重载。如果我添加第二种类型,这将产生歧义错误。我已经尝试过 google-in,但我唯一能找到的就是标签调度,但这会使用户端的调用变得丑陋。我正在考虑使用宏定义将getStringAs<std::string> 替换为调度标记的非常丑陋的解决方案。
谢谢!
【问题讨论】:
-
你为什么有
is_arithmetic支票? -
如果这是
getStringAs的完整定义,那么就没有必要了。如果您有一个重载>>的类,并且您希望将字符串作为该类获取?如果您删除 SFINAE,那么这将起作用。 -
如果您想确保只能使用算术类型(而不是具有重载运算符的类),那么您可以在函数体中添加
static_assert并获得更好的错误消息。跨度>
标签: c++ c++11 templates sfinae template-specialization