gpt4 book ai didi

c++ - 了解 SFINAE

转载 作者:IT老高 更新时间:2023-10-28 22:59:27 25 4
gpt4 key购买 nike

据我所知,SFINAE 意味着替换失败不会导致编译错误,而只是从可能的重载列表中删除原型(prototype)。

我不明白的地方:为什么是 SFINAE:

template <bool C, typename T = void> struct enable_if{};
template <typename T> struct enable_if<true, T> { typedef T type; };

但这不是?

template <bool C> struct assert;
template <> struct assert<true>{};

据我了解,这里的基本逻辑是相同的。这个问题来自对 this answer 的评论。 .

最佳答案

在 C++98 中,SFINAE 是通过返回类型或带有默认参数的函数的虚拟参数来完成的

// SFINAE on return type for functions with fixed arguments (e.g. operator overloading)
template<class T>
typename std::enable_if< std::is_integral<T>::value, void>::type
my_function(T const&);

// SFINAE on dummy argument with default parameter for functions with no return type (e.g. constructors)
template<class T>
void my_function(T const&, std::enable_if< std::is_integral<T>::value, void>::type* = nullptr);

在这两种情况下,为了得到嵌套类型type而替换T是SFINAE的本质。与 std::enable_if 相比,您的 assert 模板没有可用于 SFINAE 替换部分的嵌套类型

查看 Jonathan Wakely 的优秀 ACCU 2013 presentation有关更多详细信息以及 C++11 表达式 SFINAE。除其他外(正如@BartekBanachewicz 在评论中指出的那样)现在也可以在函数模板默认参数中使用 SFINAE

// use C++11 default function arguments, no clutter in function's signature!
template<class T, class dummy = typename std::enable_if< std::is_integral<T>::value, void>::type>
void my_function(T const&);

关于c++ - 了解 SFINAE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17829874/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com