c++ - 模板函数不会编译

标签 c++ templates

这是我的模板函数

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/

相关文章:

go - 有没有一种方法可以计算Go模板?

c++ - 如何为模板类重载 % 运算符?

c++ - 调用专门未模板化的函数

文件的 C++ 输出流不起作用

c++ - 在 C++ 中获取所有排列的最有效方法

c++ - 如何使用全局键盘 Hook 发送键?

c++ - 模板函数导致找不到标识符

c++ - 为什么我不能定义一个一元运算符,然后在 MSVC 的模板类中声明一个同名的友元二元运算符?

c++ - QDataStream QIODevice 内存分配

C++11 : cin doesn't wait for user input and ends the loop