Templatized branchless int max/min function

后端 未结 5 681
故里飘歌
故里飘歌 2021-02-05 17:34

I\'m trying to write a branchless function to return the MAX or MIN of two integers without resorting to if (or ?:). Using the usual technique I can do this easily enough for a

5条回答
  •  佛祖请我去吃肉
    2021-02-05 18:14

    Here's another approach for branchless max and min. What's nice about it is that it doesn't use any bit tricks and you don't have to know anything about the type.

    template  
    inline T imax (T a, T b)
    {
        return (a > b) * a + (a <= b) * b;
    }
    
    template  
    inline T imin (T a, T b)
    {
        return (a > b) * b + (a <= b) * a;
    }
    

提交回复
热议问题