当一个人说SFINAE友好的时候是什么意思? [英] What does it mean when one says something is SFINAE-friendly?

查看:198
本文介绍了当一个人说SFINAE友好的时候是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我们提到某个特定的函数,结构或...是 SFINAE友好时,我无法清楚地了解它的含义。

I can't clearly get the grasp of what it means when one mentions that a particular function, struct or ... is SFINAE-friendly.

有人可以解释一下吗?

推荐答案

c> static_assert )。

When it allows substitution failure without hard error (as static_assert).

例如

template <typename T>
void call_f(const T& t)
{
    t.f();
}

函数声明为 T f ,所以你不能在 call_f< WithoutF> 上做SFINAE。因为该方法确实存在。 (演示非编译代码)。

The function is declared for all T, even those with don't have f, so you cannot do SFINAE on call_f<WithoutF> as the method does exist. (Demo of non compiling code).

随以下更改:

template <typename T>
auto call_f(const T& t) ->decltype(t.f(), void())
{
    t.f();
}

该方法仅对有效的T存在 only b $ b,因此您可以使用SFINAE作为

The method exists only for valid T. so you can use SFINAE as

template<typename T>
auto call_f_if_available_impl(const T& t, int) -> decltype(call_f(t))
{
    call_f(t);
}

template<typename T>
auto call_f_if_available_impl(const T& t, ...)
{
    // Do nothing;
}

 template<typename T>
 auto call_f_if_available(const T& t)
 {
    call_f_if_available_impl(t, 0);
 }

注意 int = 0 ... 是命令重载。
演示

Note the int = 0 and ... is to order the overload. Demo

-

另一种情况是模板添加特殊参数以应用SFINAE进行特殊化:

An other case is when the template add special parameter to apply SFINAE for specialization:

template <typename T, typename Enabler = void> struct S;

然后

// Specialization only available for T which respect the traits.
template <typename T>
struct S<T, std::enable_if_t<my_type_trait<T>::value>>
{
};

这篇关于当一个人说SFINAE友好的时候是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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