2012-02-09 86 views
1

这里是我的模板函数模板功能将无法编译

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) 
+1

我认为你可以从字面上写'return(std :: stringstream()<< * value);'在一行中。 – 2012-02-09 19:11:22

回答

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"); 
//.... 

所以,你需要执行移到头:

//header.h 

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

我在编译这个时遇到了一些编译错误,也许你的代码有些不同。无论如何,如果你达到了链接阶段,这应该做到这一点。 – 2012-02-09 19:08:55

+0

哦,谢谢。我认为我的代码中有一些错误,我试图复制stringstream,因为它不可复制。无论如何,原来的问题已经解决。我需要将所有模板定义放在头文件中。 – 2012-02-09 19:12:11

+0

@NegativeZero yup,这就是模板的工作原理。编译器会在第一次遇到特殊情况时为其生成代码,因此它需要访问同一翻译单元中的代码。 – 2012-02-09 19:13:20

0

有几件事情你的代码错误: *我不认为你打算只是将字符串的第一个字符添加到您的流 因此*value没有多大意义

  • stringstream没有赋值运算符或复制构造函数 因此retval = retval << *value也没有意义。

缺少模板函数的常见原因是您忘记在.cpp文件中实例化模板。你是这样做的

template std::stringstream logging_expansion<char>(char const *value);