Difference between SFINAE and tag dispatch

为君一笑 提交于 2021-01-23 06:38:04

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/58630192/difference-between-sfinae-and-tag-dispatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!