Difference between SFINAE and tag dispatch
Asked Answered
A

1

7

In this video https://youtu.be/Vkck4EU2lOU?t=582 "tag dispatch" and SFINAE are being presented as the alternatives, allowing to achieve selection of the desired template function.

Is it correct? Isn't "tag dispatch" using SFINAE? If it's correct, what is the difference between SFINAE and tag dispatch exactly?

Anticipant answered 30/10, 2019 at 16:48 Comment(1)
can you include some relevant context in your question? Not everybody can watch the videoInglis
B
12

Tag dispatch takes advantage of overload resolution to select the right overload.

auto f_impl(std::true_type) { return true; }
auto f_impl(std::false_type) { return std::string("No"); }

template <class T>
auto f(const T& t) {
    return f_impl(std::is_integral<T>());
}

SFINAE disables a candidate by making it ineligible due to substitution failure.
Substitution failure is just what it says on the tin: Trying to substitute concrete arguments for the template parameters and encountering an error, which in the immediate context only rejects that candidate.

template <class T>
auto f(const T& t)
-> std::enable_if_t<std::is_integral_v<T>, bool> {
    return true;
}
template <class T>
auto f(const T& t)
-> std::enable_if_t<!std::is_integral_v<T>, std::string> {
    return std::string("No");
}

Sometimes, one or the other technique is easier to apply. And naturally they can be combined to great effect.

Complementary techniques are partial and full specialization. Also, if constexpr can often simplify things.

Battlefield answered 30/10, 2019 at 17:14 Comment(2)
what is the definition of substitution failure?Anticipant
@Anticipant Given a function call the compiler takes the types of the arguments the user has passed to it and tries to match (substitute) them with the "most proper" function declaration in scope (I don't need to mention that all candidate functions have the same name). Thus, when a declared function does not match with the call, we have a substitution failure and the compiler proceeds on searching for a better match.Earthnut

© 2022 - 2024 — McMap. All rights reserved.