这是我的模板功能

template<typename T> std::stringstream logging_expansion ( T const * value ){
    std::stringstream retval;
    retval = retval << *value;
    return retval;
}

这是我称之为使用它的方式
logging_expansion( "This is the log comes from the convinient function");

但是链接器告诉我它不能引用该函数:
Undefined symbols for architecture x86_64:
  "std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >     logging_expansion<char>(char const*)", referenced from:
  _main in WirelessAutomationDeviceXpcService.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

最佳答案

您需要在头文件中提供模板功能的实现,或在头中定义特殊化。

我假设您当前有类似的东西:

//header.h
template<typename T> std::stringstream logging_expansion ( T const * value );

//implementation.cpp
#include "header.h"

template<typename T> std::stringstream logging_expansion ( T const * value ){
    std::stringstream retval;
    retval = retval << *value;
    return retval;
}

//main.cpp
#include "header.h"

//....
logging_expansion( "This is the log comes from the convinient function");
//....

因此,您需要将实现移至 header :
//header.h

template<typename T> std::stringstream logging_expansion ( T const * value ){
    std::stringstream retval;
    retval = retval << *value;
    return retval;
}

关于c++ - 模板功能无法编译,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9217061/

10-10 21:25