C ++模板,未定义引用 [英] C++ templates, undefined reference
问题描述
我有一个函数声明如下:
template< typename T&
T read();
并定义如下:
template< typename T>
T packetreader :: read(){
offset + = sizeof(T);
return *(T *)(buf + offset-sizeof(T));但是,当我尝试在我的main()函数中使用它: / p>
数据包读取器;
reader.read< int>();
我从g ++得到以下错误:
g ++ -o main main.o packet.o
main.o:在main函数中:
main.cpp :(。text + 0xcc):未定义引用`int packetreader :: read< int>()'
collect2:ld返回1退出状态
make:*** [main]错误1
任何人都可以指向正确的方向?
解决方案您需要使用 export
关键字。但是,我不认为G ++有适当的支持,所以你需要在标题中包含模板函数的定义,以便翻译单元可以使用它。这是因为尚未创建模板的< int>
'版本',只有< typename T>
'version。'
一个简单的方法是 #include
.cpp文件。然而,这可能导致问题,例如,当其他函数在.cpp文件中。它也可能会增加编译时间。
一个干净的方式是将你的模板函数移动到自己的.cpp文件中,并包含在标题
I have a function declared like so:
template <typename T>
T read();
and defined like so:
template <typename T>
T packetreader::read() {
offset += sizeof(T);
return *(T*)(buf+offset-sizeof(T));
}
However, when I try to use it in my main() function:
packetreader reader;
reader.read<int>();
I get the following error from g++:
g++ -o main main.o packet.o
main.o: In function `main':
main.cpp:(.text+0xcc): undefined reference to `int packetreader::read<int>()'
collect2: ld returned 1 exit status
make: *** [main] Error 1
Can anyone point me into the right direction?
解决方案 You need to use the export
keyword. However, I don't think G++ has proper support, so you need to include the template function's definition in the header so the translation unit can use it. This is because the <int>
'version' of the template hasn't been created, only the <typename T>
'version.'
An easy way is to #include
the .cpp file. However, this can cause problems, e.g. when other functions are in the .cpp file. It will also likely increase the compile time.
A clean way is to move your template functions into its own .cpp file, and include that in the header or use the export
keyword and compile it separately.
这篇关于C ++模板,未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!