2017-08-05 32 views
0

我正在研究模板专业化,但无法理解混合类和int。混合类和int函数模板专业化

以下代码无法编译click to compile。有人可以在这里提出正确的方法。我希望专注于int类。第二个模板m应该定义为0,但是如何指定。

#include <iostream> 
using namespace std; 

template <class T,int m> 
void fun(T a) 
{ 
cout << "The main template fun(): " << a << " " << m << endl; 
} 

template<> 
void fun(int a) 
{ 
    cout << "Specialized Template for int type: " << a << endl; 
} 

int main() 
{ 
    fun<char,10>('a'); 
    fun<int,20>(10); 
    fun<float,12>(10.14); 
} 

的错误是:

prog.cpp:11:6: error: template-id 'fun<>' for 'void fun(int)' does not match any template declaration 
void fun(int a) 
    ^
+0

你不能部分专门化功能,只要你想。 – Jarod42

回答

3

我建议修改参数,以令T被推断,然后只需使用过载:

template <int m, class T> 
void fun(T a) 
{ 
    cout << "The main template fun(): " << a << " " << m << endl; 
} 

template <int m> 
void fun(int a) 
{ 
    cout << "Template for int type: " << a << endl; 
} 

的使用方式:

fun<10>('a'); 
fun<20>(10); 
fun<12, float>(10.14); // or simply fun<12>(10.14f); 
1

我假设你是什么要做的是专门化模板,以便任何形式的呼叫

fun<int, N>(...); 

调用专业化?

对于int,这需要fun()的部分专业化,但C++语言禁止部分专用功能模板。但是,我们可以部分专门化类模板。因此,一种方法做你想要将实现你的fun()使用功能的函数对象,像这样的内容:

// General case 
template <typename T, int N> 
struct do_fun { 
    void operator()(T a) { 
     cout << "The main template fun(): " << a << " " << N << endl; 
    } 
}; 

// Specialisation for int 
template <int N> 
struct do_fun<int, N> { 
    void operator()(int a) { 
     cout << "Specialized Template for int type: " << a << endl; 
    } 
}; 

然后,您可以提供使用该函数对象的包装函数模板:

template <typename T, int N> 
void fun(T a) { 
    do_fun<T, N>{}(a); 
} 

Coliru example