C++函数模板: can't match the best function

标签 c++ templates

我尝试将不同类型的 C++ 变量写入字节数组,这是我的代码:


    typedef unsigned char byte;

    template<typename T>
    using remove_rcv = typename std::remove_cv_t<std::remove_reference_t<T>>;
    
    template<typename T>
    size_t write(byte* p, T&& x) {
        static_assert(std::is_trivial_v<T>, "write() do not support this type");
        const byte* px = reinterpret_cast<const byte*>(&x);
        for (int i = 0; i < sizeof(remove_rcv<T>); i++) {
            p[i] = px[i];
        }
        return sizeof(remove_rcv<T>);
    }
    template<typename T>
    size_t write(byte* p, const std::vector<T>& x) {
        size_t len = 0;
        for (int i = 0; i < x.size(); i++) {
            len += write(p + len, x[i]);
        }
    }

如你所见,我使用第一个 write函数来编写内置类型或简单的 struct第二个写 vector<T>

但是在这段代码中:

byte buf[1024];
std::vector<int> v = { 12,34,56 };
write(buf, v);

write(buf, v);会调用第一个函数,为什么?

第二个函数不是最适合此调用吗?

我发现让它发挥作用的唯一方法是:write<int>(buf, v);但我不想这样做,因为 write将在另一个模板函数中调用。

那我该怎么解决呢?

编辑:

我尝试将第二个函数修改为普通函数:

size_t write(byte* p, const std::vector<int>& x) {
    size_t len = 0;
    for (int i = 0; i < x.size(); i++) {
        len += write(p + len, x[i]);
    }
}

也无法匹配。多么奇怪!

最佳答案

将第一个函数的签名更改为 const T&,然后第二个函数是更好的匹配。

    template<typename T>
    size_t write(byte* p, const T& x) 

    template<typename T>
    size_t write(byte* p, const std::vector<T>& x)

关于C++函数模板: can't match the best function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66504731/

相关文章:

iphone - FMOD 用完 channel ,FMOD_CHANNEL_FREE 似乎不起作用

c++ - 推导函数返回类型的常量

c++ - 警告 : non-constant array size in new, 无法验证初始化列表的长度

c++ - QTableView如何以编程方式选择多列

c++ - 模板类 : No default constructor

c++ - 数组反向 - XOR 比使用临时对象切换慢

wpf - DataTemplateSelector 不会被使用

c++ - 如何防止模板类的实例化?

c++ - 使用 C++ 模板更改操作

c++ - 基于 SFINAE 的重载冲突