這一直讓我發瘋。我正在嘗試將類型轉換爲字節並返回,這是我工作的。當我圍繞我的方法構建函數時,我得到了模板推理錯誤,但我無法看出它應該發生的任何原因。我的繼承人代碼:爲什麼模板參數扣除/替換失敗?
#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;' –