SFINAE和标签调度的区别 [英] Difference between SFINAE and tag dispatch

查看:49
本文介绍了SFINAE和标签调度的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在此视频中https://youtu.be/Vkck4EU2lOU?t=582标签dispatch" 和 SFINAE 作为替代方案被提出,允许实现对所需模板函数的选择.

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.

正确吗?不是使用 SFINAE 的标签调度"吗?如果是正确的,SFINAE 和标签分发到底有什么区别?

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

推荐答案

标签调度利用重载解析来选择正确的重载.

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 因替换失败而使候选人失去资格,从而禁用候选人.
替换失败正如它所说的那样:尝试替换模板参数的具体参数并遇到错误,在直接上下文中只会拒绝该候选.

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.

补充技术是部分专业化和完全专业化.此外,if constexpr 通常可以简化事情.

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

这篇关于SFINAE和标签调度的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆