这一直让我发疯。我正在尝试将类型转换为字节并返回,这是我工作的。当我围绕我的方法构建函数时,我得到了模板推理错误,但我无法看出它应该发生的任何原因。我的继承人代码:为什么模板参数扣除/替换失败?
#include <iostream>
#include <vector>
using namespace std;
template<typename T>
uint8_t *to_bytes(T &val) {
return reinterpret_cast<uint8_t *>(&val);
};
template<typename T>
T *from_bytes(uint8_t *bytes) {
return reinterpret_cast<T *>(bytes);
};
int main() {
double a = 10.4;
uint8_t *bytevals = to_bytes(a);
// "Send" the data out and receive it into an array
uint8_t bytes_rx[sizeof(a)];
for (int byt_ndx = 0; byt_ndx < sizeof(a); ++byt_ndx) {
bytes_rx[byt_ndx] = bytevals[byt_ndx];
}
double *thing_back;
thing_back = from_bytes(&bytes_rx[0]);
cout << *thing_back;
}
当我建立错误:
C:\Users\Peter\CLionProjects\CodingPractice\main.cpp: In function 'int main()':
C:\Users\Peter\CLionProjects\CodingPractice\main.cpp:31:41: error: no matching function for call to 'from_bytes(uint8_t*)'
thing_back = from_bytes(&bytes_rx[0]);
^
C:\Users\Peter\CLionProjects\CodingPractice\main.cpp:14:4: note: candidate: template<class T> T* from_bytes(uint8_t*)
T *from_bytes(uint8_t *bytes) {
^
C:\Users\Peter\CLionProjects\CodingPractice\main.cpp:14:4: note: template argument deduction/substitution failed:
C:\Users\Peter\CLionProjects\CodingPractice\main.cpp:31:41: note: couldn't deduce template parameter 'T'
thing_back = from_bytes(&bytes_rx[0]);
值得一提的,如果我替换功能,在该功能的代码直接调用,一切正常。
不要使用'使用命名空间std;' –