2017-08-05 36 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