模板函数的模板特化声明

Declaration of template specialization on a template function

我正在获得 undefined reference to ´long long fromBigEndin<long long>(unsigned char*)´ 模板专业化。

查看代码:https://onlinegdb.com/AagKTQJ2B

我有这样的结构:

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);
}

根据@AnoopRana 的回复,将实现放在头文件中是可行的,我想知道是否可以将实现放在单独的文件中。

关于如何强制编译 fromBigEndin<int64_t>() 的任何想法?

我也试过将专业化转移到 util.cpp 但也没有用。

代码本身在单个文件中使用不同的声明时有效:

方法一

您需要将函数模板的实现放入头文件本身。所以它看起来像:

util.h

#pragma once  //include guard added
template <class T>
T fromBigEndin(uint8_t *buf);

//definition
template <> int64_t fromBigEndin<int64_t>(uint8_t *buf)
{
    return 53;
}
//definition 
template <> long long fromBigEndin<long long>(unsigned char *buf)
{ 
    return 54;
}


//implementation in header file itself
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

#pragma once
#include "util.h"

void handleOpenSession(uint8_t *data) {
    //add code here 
}

main.cpp

#include <iostream>
#include "util.h"
int main()
{
    
    return 0;
}

Working demo

方法二

这里我们使用显式模板实例化。

util.h

#pragma once
#include <cstdint>
template <class T>
T fromBigEndin(uint8_t *buf);


headerImpl.h

#pragma once
#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);
}

util.cpp

#include "util.h"

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;
}

//no angle brackets used here
template int64_t fromBigEndin<int64_t>(uint8_t *buf);
template long long fromBigEndin<long long>(unsigned char *buf);

main.cpp


#include <iostream>

#include "util.h"
int main()
{
    
    return 0;
}

Working demo