2017-04-08 87 views
1

这一直让我发疯。我正在尝试将类型转换为字节并返回,这是我工作的。当我围绕我的方法构建函数时,我得到了模板推理错误,但我无法看出它应该发生的任何原因。我的继承人代码:为什么模板参数扣除/替换失败?

#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]); 

值得一提的,如果我替换功能,在该功能的代码直接调用,一切正常。

+0

不要使用'使用命名空间std;' –

回答

3

模板参数T未在函数的参数中使用。因此,T不能从用于调用它的参数中推导出来。

您需要明确模板参数。

thing_back = from_bytes<double>(&bytes_rx[0]); 

如果您反对显式使用模板参数,则可以使用函数的伪参数。

template<typename T> 
T *from_bytes(uint8_t *bytes, T* dummy) { 
    return reinterpret_cast<T *>(bytes); 
}; 

,并用它作为:

thing_back = from_bytes(&bytes_rx[0], things_back); 
+0

非常感谢!我在考虑将'double * thing_back'设置为从from_bytes(&bytes_rx [0])返回的值就足以通知模板。它怎么会不能?我可以看到这种方法可能不灵活,但我对一个原因没有信心。 –

+0

@LordGonk,函数的返回值所分配的对象的类型永远不会用于推断调用哪个函数。这不仅适用于函数模板,也适用于普通函数 - 成员函数和非成员函数。 –