C++ 当一个人说某事对SFINAE友好时,这意味着什么?

C++ 当一个人说某事对SFINAE友好时,这意味着什么?,c++,sfinae,C++,Sfinae,当一个人提到一个特定的函数、结构或是。。。斯菲那友好吗 有人能解释一下吗?当它允许替换失败而没有硬错误时(如static\u assert) 比如说 template <typename T> void call_f(const T& t) { t.f(); } 该方法仅存在于有效T的中。 因此,您可以使用SFINAE作为 template<typename T> auto call_f_if_available_impl(const T& t,

当一个人提到一个特定的函数、结构或是。。。斯菲那友好吗


有人能解释一下吗?

当它允许替换失败而没有硬错误时(如
static\u assert

比如说

template <typename T>
void call_f(const T& t)
{
    t.f();
}
该方法仅存在于有效T的中。 因此,您可以使用SFINAE作为

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);
 }
然后

// Specialization only available for T which respect the traits.
template <typename T>
struct S<T, std::enable_if_t<my_type_trait<T>::value>>
{
};
//专门化仅适用于尊重特征的T。
模板
结构
{
};

如果一个实体可以在SFINAE环境中使用而不会在替换失败时产生硬错误,则该实体被称为SFINAE友好实体。我想你已经知道SFINAE是什么了,因为这本身就是一个完全不同的问题

< >在C++标准化的上下文中,SfayAe友好的术语至今已应用于<代码> STD::<代码/>和<代码> STD::CuyMyType < /C>。以以下为例:

template <typename T>
void foo(T x, typename std::common_type<T, int>::type y) {}

void foo(std::string x, std::string y) {}

int main()
{
    foo(std::string("hello"), std::string("world"));
}

如果没有的SFINAE-friendly
result\u,这将无法编译,因为
std::result\u of::type将在模板参数替换期间产生硬错误。随着()的SFINAE友好
结果的引入,该示例的格式变得良好,因为
std::result\u of::type
会产生替换失败,从而将重载从可行集中排除。

不是
int=0
vs
模棱两可吗?你的意思是什么:你不能在
调用f
时执行SFINAE?@TartanLlama不,这不是因为
int
更专业。
是的,这是模棱两可的。它不会编译。这解释了什么是SFINAE,但不是SFINAE友好的东西(例如N3462和N3843)的含义。
// Specialization only available for T which respect the traits.
template <typename T>
struct S<T, std::enable_if_t<my_type_trait<T>::value>>
{
};
template <typename T>
void foo(T x, typename std::common_type<T, int>::type y) {}

void foo(std::string x, std::string y) {}

int main()
{
    foo(std::string("hello"), std::string("world"));
}
template <typename T>
auto bar(T f) -> typename std::result_of<T()>::type { return f(); }

void bar(int n) {}

int main()
{
    bar(42);
}