【发布时间】:2021-12-20 13:38:22
【问题描述】:
我有一个模板函数,它应该执行不同的代码,具体取决于类型。简化后的函数如下所示:
template<typename T>
std::string test(T value)
{
std::string v;
if(std::is_arithmetic<T>())
{
v = std::to_string(value);
}
else
{
v = std::string(value);
}
return v;
}
用法:
test("Hello");
test(123);
但我收到此错误:
In instantiation of void test(T) [with T = const char*]:
error: no matching function for call to to_string(const char*)
note: candidate: std::string std::__cxx11::to_string(int) <near match>
to_string(int __val)
and the same for the following:
to_string(unsigned __val)
to_string(long __val)
to_string(unsigned long __val)
好的,我知道,例如const char *,编译将失败,因为没有std::to_string(const char *)。但我怎样才能使代码工作?只需要注意,在我的真实代码中,我限制为c++11。
【问题讨论】:
-
if constexpr(std::is_arithmetic<T>())。如果你不能使用它,你需要使用 SFINAE 和两个不同的模板