模板函数不会编译

Neg*_*ero 1 c++ templates

这是我的模板功能

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

以下是我如何称它使用它

logging_expansion( "This is the log comes from the convinient function");
Run Code Online (Sandbox Code Playgroud)

但链接器告诉我它无法引用该函数:

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)
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 5

您需要在头文件中提供模板函数的实现,或者在头文件中定义特化.

我假设你现在有类似的东西:

//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");
//....
Run Code Online (Sandbox Code Playgroud)

所以你需要将实现移动到标题:

//header.h

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