Templatized branchless int max/min function

后端 未结 5 623
故里飘歌
故里飘歌 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:20

    I don't know what are the exact conditions for this bit mask trick to work but you can do something like

    #include
    
    template{}> > 
    inline T imax( T a, T b )
    {
       ...
    }
    

    Other useful candidates are std::is_[un]signed, std::is_fundamental, etc. https://en.cppreference.com/w/cpp/types

提交回复
热议问题