为什么链接器抱怨该模板中有多个定义?
当包含在至少两个翻译单元(cpp 文件)中时,这一小段代码会触发链接器的愤怒:
# ifndef MAXIMUM_HPP
# define MAXIMUM_HPP
template<typename T>
T maximum(const T & a, const T & b)
{
return a > b ? a : b ;
}
/* dumb specialization */
template<>
int maximum(const int & a, const int & b)
{
return a > b ? a : b ;
}
# endif // MAXIMUM_HPP
但是使用一个翻译单元可以很好地编译和链接。如果我删除专业化,它在所有情况下都可以正常工作。这是链接器消息:
g++ -o test.exe Sources\test.o Sources\other_test.o
Sources\other_test.o:other_test.cpp:(.text+0x0): multiple definition of `int maximum<int>(int const&, int const&)'
Sources\test.o:test.cpp:(.text+0x14): first defined here
模板不允许多次实例化吗?如何解释这个错误以及如何修复它?
感谢您的任何建议!
This little piece of code triggers the linker's anger when included on at least two translation units (cpp files) :
# ifndef MAXIMUM_HPP
# define MAXIMUM_HPP
template<typename T>
T maximum(const T & a, const T & b)
{
return a > b ? a : b ;
}
/* dumb specialization */
template<>
int maximum(const int & a, const int & b)
{
return a > b ? a : b ;
}
# endif // MAXIMUM_HPP
But compiles and links fine with one translation unit. If I remove the specialization, it works fine in all situations. Here is the linker message :
g++ -o test.exe Sources\test.o Sources\other_test.o
Sources\other_test.o:other_test.cpp:(.text+0x0): multiple definition of `int maximum<int>(int const&, int const&)'
Sources\test.o:test.cpp:(.text+0x14): first defined here
Aren't templates allowed to be instantiated multiple times ? How to explain this error and how to fix it ?
Thanks for any advice !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为完整的显式模板专业化只能定义一次 - 虽然链接器允许多次定义隐式专业化,但它不允许显式专业化,它只是将它们视为普通函数。
要修复此错误,请将所有专业化放入源文件中,例如:
Its because complete explicit template specializations must be defined only once - While the linker allows implicit specializations to be defined more than once, it will not allow explicit specializations, it just treats them as a normal function.
To fix this error, put all specializations in source file like:
内联声明函数
Declare the functions inline