Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between SFINAE and tag dispatch

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?

like image 451
user2449761 Avatar asked Oct 30 '19 16:10

user2449761


People also ask

What is Sfinae used for?

SFINAE is used to enable iterator type conversions.

Will concepts replace Sfinae?

So the simple answer is YES.


1 Answers

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.

like image 162
Deduplicator Avatar answered Oct 23 '22 22:10

Deduplicator