c.bear
c.bear

Reputation: 1445

How can I partially specialize a function template?

I can't explain myself why partial template specialization is not possible in the case below. Is there any technical reason? And mostly, is there any work around to make it work?

template <int a, int b>
void foo();

// DO NOT COMPILE
template <int a>
void foo<a, 999>() {
}

// COMPILE
template <>
void foo<999, 999>() {
}

template <int a, int b>
void foo() {
}

Upvotes: 1

Views: 110

Answers (2)

Jarod42
Jarod42

Reputation: 217265

You may use struct for partial specialization:

template <int a, int b> struct foo_helper { void operator()() { /*code*/ } };

template <int a> struct foo_helper<a, 999> { void operator()() { /*code*/ } };

template <> struct foo_helper<999, 999> { void operator()() { /*code*/ } };


template <int a, int b>
void foo()
{
    foo_helper<a, b>{}();
}

Upvotes: 3

SergeyA
SergeyA

Reputation: 62563

Functions can not be partially specialized. Usually it is much easier to overload a function or use SFINAE.

If it is not possible - like in this case, since SFINAE and overloads can only work on types - one can partially specialize a class having said function as it's static member - though it is usually more typing.

Upvotes: 3

Related Questions