SFINAE的表现以及其他

Yve*_*ves 0 c++ cpu performance sfinae

我知道这if else可能会产生Pipeline停顿(气泡),因为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
}
Run Code Online (Sandbox Code Playgroud)

这样我们避免

if (I % 2 == 0)
{
    // do things
}
else
{
    // do other things
}
Run Code Online (Sandbox Code Playgroud)

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

Jos*_*ica 5

从运行时性能的角度来看,您所做的根本不重要。要么I在编译时就可以知道,在这种情况下,任何一个像样的编译器都会为两者输出相同的常量大小写,否则就不会,在这种情况下,SFINAE方式根本不会编译。