我有一个模板函数,它应该执行不同的代码,具体取决于类型。简化后的函数如下所示:
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
添加到语言中。如果您需要在更大的算法中执行一些依赖于类型的操作,那么在 C++17 之前的版本中,执行此操作的方法通常是通过 tag-dispatch
namespace detail {
template<typename T>
std::string stringify(T value, std::true_type) {
return std::to_string(value);
}
template<typename T>
std::string stringify(T value, std::false_type) {
return std::string(value);
}
}
template<typename T>
std::string test(T value)
{
std::string v;
v = detail::stringify(value, std::is_arithmetic<T>());
return v;
}
这是在两个条件下进行调度,但该技术可以扩展到多个重载,具体取决于您如何构建标签类型。标准中的一个常见示例是 iterator categories .
关于C++ 条件执行取决于类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69871195/