我想学习更多的模板元编程。我知道 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/