【发布时间】:2014-05-25 19:39:27
【问题描述】:
当模板参数类型相同时,我正在尝试专门化两个模板参数的函数。我这样做的方式如下:
#include <iostream>
#include <type_traits>
using namespace std;
template<typename U, typename T>
int fun( U& u, T t );
template<>
inline
int fun( int& u, float t )
{
cout << "int, float" << endl;
return 0;
}
template<typename U, typename T>
inline
int fun( U& u, typename std::enable_if<std::is_same<U, T>::value ,T>::type t )
{
cout << "U == T" << endl;
return 0;
}
int main()
{
int a;
float b1, b2;
fun(a, b1);
fun(b1, b2);
return 0;
}
这段代码编译得很好(GCC 4.8.2),但是当U 和T 是同一类型时,链接器会为所有fun 调用提供未定义的引用。为什么它不起作用?
链接器输出:
g++ -std=c++11 test.cpp
/tmp/cc7HWboz.o: In function `main':
test.cpp:(.text+0x66): undefined reference to `int fun<float, float>(float&, float)'
collect2: error: ld returned 1 exit status
【问题讨论】:
-
T和U不同时是否没有链接器错误? -
@KerrekSB 正确,具体示例见编辑后的帖子
标签: c++ templates c++11 linker specialization