SFINAE的性能,如果不是

The performance of SFINAE and if else

本文关键字:如果不 性能 SFINAE      更新时间:2023-10-16

我知道if else可能会生成管道停滞(气泡(,因为 Branch 预测器无法保持 100% 的正确猜测。总之,很多if elif elif ... else的表现都很糟糕。

在C++的模板中,我们有SFINAE。使用 SFINAE,我们可以避免if else代码。例如,要检查 int 是否为奇数,我们可以按如下方式编码:

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

这样我们就可以避免

if (I % 2 == 0)
{
    // do things
}
else
{
    // do other things
}

我的问题是,SFINAE与if else相比有更好的性能吗?SFINAE可以避免管道泡沫吗?

从运行时性能的角度来看,你做哪一个根本不重要。 任何一个I在编译时都是可知的,在这种情况下,任何半体面的编译器都会为两者输出相同的常量情况,或者不是,在这种情况下,SFINAE 方式根本不会编译。