Tags

The short of template function partial specialization is that it is not allowed, however we can emulate this feature through the use of partially specialized template classes and wrapper function(s).

This is what we’d like to be able to write:

template<typename T1, typename T2>
void foo(T1 const& t1, T2 const& t2)
{
   std::cerr << "In foo<T1, T2>(" << t1 << ", " << t2 << ")\n";
}

template<typename T2>
void foo<int, T2>(int t1, T2 const& t2)
{
   std::cerr << "In foo<int, T2>(" << t1 << ", " << t2 << ")\n";
}

Then foo(1.0, “str”) would call the first form and foo(1, “str”) would call the second form. Unfortunately the second form is illegal.

A simple work around for this is the following.

template<typename T1, typename T2>
struct Bar
{
 void operator()(T1 const& t1, T2 const& t2)
 {
    std::cerr << "In Bar<T1, T2>(" << t1 << ", " << t2 << ")\n";
 }
};
template<typename T2>
struct Bar<int, T2>
{
 void operator()(int t1, T2 const& t2)
 {
    std::cerr << "In Bar<int, T2>(" << t1 << ", " << t2 << ")\n";
 }
};
template<typename T1, typename T2>
void bar(T1 const& t1, T2 const& t2)
{
   Bar<T1, T2> b;
   b(t1, t2);
}

We have just a single function, bar, whose implementation is simply to defer to the class Bar, which can be partially specialized. Now when we write bar(1.0, “str”)Bar<T1, T2>::operator() is called and when we write bar(1, “str”), Bar<int, T2>::operator() is called.

We have successfully emulated partial specialization of template functions.

Advertisements