我尝试将不同类型的 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/