function template specialization for mixed class and int

时间:2017-08-05 10:48:16

标签: c++ templates template-specialization

I was studying about template specialization but unable to understand mixed class and int.

The following code fails to compile click to compile. Can someone suggest the right way here. I wish to specialize for int class. the second template m should be defined as 0 but how to specify that.

#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);
}

The error is:

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

2 个答案:

答案 0 :(得分:3)

I suggest to change order of parameter to let T be deduced, then simply use overload:

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;
}

With usage:

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

答案 1 :(得分:1)

I assume that what you're trying to do is to specialise the template so that any call of the form

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

Calls the specialisation?

This would require a partial specialisation of fun() for int, but the C++ language forbids partially specialising function templates. However, we can partially specialise class templates just fine. So one approach to do what you want would be to implement your fun() function using function objects, like so:

// 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;
    }
};

You can then supply a wrapper function template that uses the function objects:

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

Coliru example

相关问题