C++ 条件执行取决于类型

标签 c++ c++11 templates

我有一个模板函数,它应该执行不同的代码,具体取决于类型。简化后的函数如下所示:

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/

相关文章:

c++ - 我正在尝试用 C++ 创建一个日志记录框架,但信息没有传递给记录器的子组件,我做错了什么?

javascript - 如何在不单击的情况下激活此 JQuery fancybox?

android - 需要指导将现有的 C++ 代码集成到 Android NDK

c++ - BOOST_PP_AUTO_REC 做什么?

c++ - 如何在另一个 CDialog 中显示嵌套的 CDialog?

c++ - 将项目 move 到列表而不复制

c++ - 键相等时 std::multimap 的自定义比较函数

c++ - 带位的长枚举

c++ - 运行时绑定(bind)和模板实例化

c++ - 需要类型名错误(模板相关错误)