mercredi 26 septembre 2018

C++ different minmax implementation

Following this question of mine: reinterpret_cast bug or UB? I would like to ask if there is possibility to make std::minmax function act safely or at least safer without any overhead? I came up with a solution like this, but I am not completely sure if it is equivalent to current minmax as generated assembly is different for stl-like implementation and mine. So the question is: what are the possible problems/drawbacks of my implementation of minmax in relation to std-like one:

//below is std-like minmax
template< class T > 
constexpr std::pair<const T&,const T&> std_minmax( const T& a, const T& b ){
    return (b < a) ? std::pair<const T&, const T&>(b, a)
            : std::pair<const T&, const T&>(a, b);
}

//below is my minmax implementation
template< class T > 
constexpr std::pair<T, T> my_minmax( T&& a, T&& b ){
    return (b < a) ? std::pair<T, T>(std::forward<T>(b), std::forward<T>(a))
            : std::pair<T, T>(std::forward<T>(a), std::forward<T>(b));
}

Live demo at godbolt.org

Aucun commentaire:

Enregistrer un commentaire