在模板功能上的模板专业化声明
我会得到对模板专业化的长长的frombigendin&lt long>(unsigned char*)的
不确定的引用。
请参阅此处: https://onlinegdb.com/aagktqj2b
我有这个结构
:
template <class T>
T fromBigEndin(uint8_t *buf);
template <>
int64_t fromBigEndin<int64_t>(uint8_t *buf);
template <>
long long fromBigEndin<long long>(unsigned char *buf);
util.cpp
template<class T>
T fromBigEndin(uint8_t *buf) {
T number = 0;
uint8_t nBytes = sizeof(T);
uint8_t i;
for (i = 0; i < nBytes; i += 1) {
number += buf[i] << (16 * (nBytes - i - 1));
}
return number;
}
headerimpl.h
#include "util.h"
void handleOpenSession(uint8_t *data) {
uint8_t *uid = (uint8_t *)malloc(8);
memcpy(uid, data + 1, 8);
int64_t uidNbr = fromBigEndin<int64_t>(uid);
}
来自@Anooprana响应,将实现放在标题文件中,我想知道是否可以将实现进行实现在单独的文件中。
关于我如何强制对frombigendin&lt; int64_t&gt;()
的汇编的想法?
我还试图将专业人士移至util.cpp
,但也不起作用。
该代码本身在单个文件中和不同声明中起作用:
I'm getting undefined reference to ´long long fromBigEndin<long long>(unsigned char*)´
for a template specialization.
See code here: https://onlinegdb.com/AagKTQJ2B
I have this structure:
util.h
template <class T>
T fromBigEndin(uint8_t *buf);
template <>
int64_t fromBigEndin<int64_t>(uint8_t *buf);
template <>
long long fromBigEndin<long long>(unsigned char *buf);
util.cpp
template<class T>
T fromBigEndin(uint8_t *buf) {
T number = 0;
uint8_t nBytes = sizeof(T);
uint8_t i;
for (i = 0; i < nBytes; i += 1) {
number += buf[i] << (16 * (nBytes - i - 1));
}
return number;
}
headerImpl.h
#include "util.h"
void handleOpenSession(uint8_t *data) {
uint8_t *uid = (uint8_t *)malloc(8);
memcpy(uid, data + 1, 8);
int64_t uidNbr = fromBigEndin<int64_t>(uid);
}
From @AnoopRana response, putting the implementation in header file works, I would like to know if it is possible to put the implementation in a separate file.
Any idea on how could I force the compilation of fromBigEndin<int64_t>()
?
I've also tried to move the specializations to util.cpp
but doesn't work either.
The code itself works when in a single file and with different declarations:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
方法1
您需要将功能模板的实现放入标题文件本身中。因此,它看起来像:
util.h
headerimpl.h
main.cpp
工作演示
方法2
这里我们使用显式模板实例。
util.h
headerimpl.h
util.cpp
main.cpp
Method 1
You need to put the implementation of the function template into the header file itself. So it would look something like:
util.h
headerImpl.h
main.cpp
Working demo
Method 2
Here we make use of explicit template instantiations.
util.h
headerImpl.h
util.cpp
main.cpp
Working demo