0
votes

I'd like to write a templatized function with two template types: one a bool and one a typename, and I'd like to specialize on the typename.

eg, this is what I want, but specialized on just a couple types for T:

template<bool b, typename T>
void foo(T val)
{
   // do different stuff based on b and type of T.
}

without the bool in there, I can do something like this:

template<typename T>
void bar(T val) {
    static_assert(false, "not implemented");
}

template<>
void bar<short>(short val) {
    printf("it's a short!\n");
}

I can't figure out the syntax for this, and the microsoft docs on specialization only cover the single-type case.

1
As far as I know partial specialization is only supported on classes. For function, you have to fully specialize. A work around is to have a function that call a class in such cases. The function could call a static function inside a templated class possibly have same template paramters as the function. You can then patially or fully specialize that class. - Phil1970

1 Answers

4
votes
template<bool B, typename T>
void foo(T const&)
{
    static_assert(false, "not implemented");
}

template<bool B>
void foo(short)
{
    printf("it's a short!\n");
}

However, this is not really specialisation, but overloading, which is completely appropriate. In fact, you could omit the general case.