How to use different overload of an inline function, depending on a compile time parameter?

让人想犯罪 __ 提交于 2019-12-12 16:15:43

问题


I have a performance critical inline function, inline T func(T a, T b, int p). It can be optimized quite a bit, if p is known to be zero. However, I can't use an 'if' and penalize all the the other cases. What I want is to optimize the function only of I know at compile-time that p is zero. Is there a clean way to do that, maybe using template magic?

EDIT

I can't use differently named function/incompatible overloads (I don't know ho to express that correctly) since the code is very low level. It is very likely, that different optimization opportunities are available on another/future processors. Thus by confining all that low level stuff in one function signature, my code only needs to be recompiled to use any type of optimization.


回答1:


it's possible using templates. have a look at Boost enable_if, it has good explanation and usage examples




回答2:


Here's another way of doing it, if Boost doesn't satisfy. The p parameter must be a literal in the call, though.

#include <iostream>

// Template this on the functions if you wanted this type templated:
typedef float T; 

template<int P>
struct Wrapper {
    static T func(T a, T b) {
        std::cout << "general case (p="<< P << ")\n";
        return (a+b)*P;
    }
};

// Template specialisation for P=0
template <>
struct Wrapper<0> {
    static T func(T a, T b) {
        std::cout << "p=0 case\n";
        return 0;
    }
};

#define func(A, B, P) \
    Wrapper<P>::func(A, B)

int main() {
    func(1,2,0);
    func(1,2,345);
}

Template specialisation isn't possible on functions, hence the need for the wrapper class.




回答3:


GCC has a __builtin_constant_p function; more information in the GCC docs. I believe you'd be able to have

inline T func(T a, T b, int p)
{
    if ( builtin_constant_p(p) && p==0 )
        // special case
    else
        // fallback
}

without any performance loss.



来源:https://stackoverflow.com/questions/5017629/how-to-use-different-overload-of-an-inline-function-depending-on-a-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!