partial specialization of function templates

josh picture josh · Feb 15, 2011 · Viewed 7.2k times · Source

In the below code snippet,

template<typename T1>
void func(T1& t)
{
    cout << "all" << endl;
}

template<typename T2>
void func(T2 &t)
{
    cout << "float" << endl;
}

// I do not want this
// template<> void func(float &t)

int main()
{
    int i; float f;
    func(i); // should print "all"
    func(f); // should print "float" 
    return 0;
}

I would like to have the templates modified which by passing any type other than float will print "all" and passing float will print "float". I do not want template specialization, instead have partial specialization which will act accordingly based on input type. How should i go about it. Thanks in advance.

Well the scenario, i'm currently facing is like, I need to have the following defined,

template<typename T1>
void func(T1 &t)
{
    cout << "t1" << endl;
}

template<typename T2>
void func(T2 &t)
{
    cout << "t2" << endl;
}

The following calls should print "t2"

func(int) // print "t2"
func(float) // print "t2"
func(string) // print "t2"

The following calls should print "t1"

func(char) // print "t1"
func(xyz) // print "t1"
...
func(abc) // print "t1"

some kind of grouping like the above where few should call the partial specialization implementation and others should call the default implementation.

Answer

Gavin Lock picture Gavin Lock · Feb 15, 2011

You can combine function overloading with templates. So:

#include <iostream>

template<typename T>
void func(T& t)
{
    std::cout << "all" << std::endl;
}

void func(float& f)
{
    std::cout << "float" << std::endl;
}

int main()
{
    int i; float f;
    func(i); // prints "all"
    func(f); // prints "float" 
    return 0;
}