C++ SFINAE 示例?

标签 c++ templates metaprogramming sfinae

我想学习更多的模板元编程。我知道 SFINAE 代表“替代失败不是错误”。但是有人可以告诉我 SFINAE 的好用处吗?

最佳答案

我喜欢使用 SFINAE 来检查 bool 条件。

template<int I> void div(char(*)[I % 2 == 0] = 0) {
    /* this is taken when I is even */
}

template<int I> void div(char(*)[I % 2 == 1] = 0) {
    /* this is taken when I is odd */
}

它可能非常有用。例如,我用它来检查使用运算符逗号收集的初始化列表是否不超过固定大小

template<int N>
struct Vector {
    template<int M> 
    Vector(MyInitList<M> const& i, char(*)[M <= N] = 0) { /* ... */ }
}

该列表仅在 M 小于 N 时才被接受,这意味着初始化列表没有太多元素。

语法char(*)[C]表示:指向元素类型为char、大小为C的数组的指针。如果 C 为假(此处为 0),那么我们得到无效类型 char(*)[0],指向零大小数组的指针:SFINAE 使得模板将被忽略。

boost::enable_if表示,看起来像这样

template<int N>
struct Vector {
    template<int M> 
    Vector(MyInitList<M> const& i, 
           typename enable_if_c<(M <= N)>::type* = 0) { /* ... */ }
}

在实践中,我经常发现检查条件的能力很有用。

关于C++ SFINAE 示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/982808/

相关文章:

r - 如何在 R 中进行部分替换?

c++模板类根据类型通过ref传递构造函数

c++ - OpenGL gluLookat 无法使用着色器

c++ - 从 VS2012 在 C++ 中使用 ATL 创建 COM

c++ - Dev cpp 中没有错误窗口

c++ - 用模板参数除以零

ruby - 提取祖先到 "me"

c++ - 我必须明确地调用 Destructor

C++ 在成员函数范围内使用语句

c++ - 模板错误 : nontype ".. [with T=T] is not a type name"