函数模板特化编译时的重定义错误

Issue:
在函数模板特化的过程中, 编译时遇到多重定义的错误; (VC2010和g++)

以下是一个特化的例子:

template <class T>
T maxA( T t1, T t2 ) {
    return (t1 > t2 ? t1 : t2);
}
//特化 specialize
typedef const char *PCC;
template<> PCC maxA< PCC >( PCC s1, PCC s2 ) {
    return ( strcmp( s1, s2 ) > 0 ? s1 : s2 );
}

1)如果这段代码是添加在main.cpp里面, 没有问题, 编译通过;

2)如果这段代码添加到头文件, e.g. test.h中, 编辑阶段就会有多重定义的error;

Solution:

a) 将函数模板的特化声明在头文件中, 定义放在cpp中;

//header-test.h
template <class T>
T maxA( T t1, T t2 ) {
    cout<<"Base"<<endl;
    return (t1 > t2 ? t1 : t2);
}
//特化 specialize
typedef const char *PCC;
template<> PCC maxA< PCC >( PCC s1, PCC s2 ) ;
//implement
//test.cpp
template<> PCC maxA< PCC >( PCC s1, PCC s2 ) {
    cout<<"Spec"<<endl;
    return ( strcmp( s1, s2 ) > 0 ? s1 : s2 );
}

b) 把特化的函数声明为inline;

template <class T>
T maxA( T t1, T t2 ) {
    cout<<"Base"<<endl;
    return (t1 > t2 ? t1 : t2);
}
//特化 specialize
typedef const char *PCC;
template<>
inline PCC maxA< PCC >( PCC s1, PCC s2 ){
    cout<<"Spec"<<endl;
    return ( strcmp( s1, s2 ) > 0 ? s1 : s2 );
}

 

Reason: 
The full specialization is no longer a template. It's a concrete function.
函数模板全特化后不再是一个模板, 它成为了一个函数的实现;
如果在头文件中全特化函数模板, 就好象在头文件中多次定义了同一个函数, 编译器就抓狂了.

 

<refer to> http://stackoverflow.com/questions/4446968/template-specialization-multiply-defined-symbols

---End---

原文地址:https://www.cnblogs.com/roymuste/p/3059428.html