为什么链接器会在此模板中抱怨多个定义?

时间:2011-10-25 00:52:14

标签: c++ templates template-specialization

当至少包含两个翻译单元(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

是否允许多次模板化实例化?如何解释这个错误以及如何修复它?

感谢您的任何建议!

2 个答案:

答案 0 :(得分:31)

因为完整的显式模板特化只能定义一次 - 虽然链接器允许多次定义隐式特化,但它不允许显式特化,它只是将它们视为正常函数。
要修复此错误,请将所有特化项放在源文件中,如:

// header

// must be in header file because the compiler needs to specialize it in
// different translation units
template<typename T>
T maximum(const T & a, const T & b)
{
    return a > b ? a : b ;
}

// must be in header file to make sure the compiler doesn't make an implicit 
// specialization
template<> int maximum(const int & a, const int & b);

// source

// must be in source file so the linker won't see it twice
template<>
int maximum(const int & a, const int & b)
{
    return a > b ? a : b ;
}

答案 1 :(得分:13)

声明函数内联

// must be in header file because the compiler needs to specialize it in
// different translation units
template<typename T>
inline T maximum(const T & a, const T & b)
{
    return a > b ? a : b ;
}

/* dumb specialization */
template<>
inline int maximum(const int & a, const int & b)
{
    return a > b ? a : b ;
}
相关问题