Home > Back-end >  SFINAE template specialization matching rule
SFINAE template specialization matching rule

Time:07-17

I'm learning about SFINE with class/struct template specialization and I'm a bit confused by the matching rule in a nuanced example.

#include <iostream>

template <typename T, typename = void>
struct Foo{
    void foo(T t)
    {
        std::cout << "general";
    }
};

template <typename T>
struct Foo<T, typename std::enable_if<std::is_integral<T>::value>::type>
{
    void foo(T t)
    {
        std::cout << "specialized";
    }
};

int main()
{
    Foo<int>().foo(3);

    return 0;
}

This behaves as expected and prints out specialized, however if I change the specialized function slightly to the following:

template <typename T>
struct Foo<T, typename std::enable_if<std::is_integral<T>::value, int>::type>
{
    void foo(T t)
    {
        std::cout << "specialized";
    }
};

then it prints out general. What's changed in the second implementation that makes it less 'specialized'?

CodePudding user response:

Re-focus your eyeballs a few lines higher, to this part:

template <typename T, typename = void>
struct Foo{

This means that when this template gets invoked here:

Foo<int>().foo(3);

This ends up invoking the following template: Foo<int, void>. After all, that's what the 2nd template parameter is, by default.

The 2nd template parameter is not some trifle, minor detail that gets swept under the rug. When invoking a template all of its parameters must be specified or deduced. And if not, if they have a default value, that rescues the day.

SFINAE frequently takes advantage of default template parameters. Now, let's revisit your proposed template revision:

template <typename T>
struct Foo<T, typename std::enable_if<std::is_integral<T>::value, int>::type>

The effect of this specialization is that the 2nd template parameter in the specialization is int, not void.

But Foo<int> is going to still use the default void for the 2nd template parameter because, well, that's the default value of the 2nd template parameter. So, only the general definition will match, and not any specialization.

CodePudding user response:

It's not that it's less specialized, it no longer matches the template instantiation. The second type parameter defaults to void, but since the std::enable_if now aliases int, the specialization no longer matches.

  • Related