【发布时间】:2011-12-14 13:49:29
【问题描述】:
当包含在至少两个翻译单元(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
模板不能被多次实例化吗?如何解释这个错误以及如何修复它?
感谢您的建议!
【问题讨论】:
-
你可能应该从你的函数中返回一个引用。
-
这只是跟踪我在更复杂的代码中遇到的错误的一个例子。我认为这个例子可以更清楚,没有任何参考:)
标签: c++ templates template-specialization