Home > Mobile >  Alias a std::min and std::max functions
Alias a std::min and std::max functions

Time:01-16

I'm trying to create aliases for std::min and std::max functions based on this answer, but if I try the following code:

#include <algorithm>
namespace math
{
   template< typename T >
   constexpr auto Max = std::max< T >;
}

then if I try to run following code:

constexpr int a = 2;
constexpr int b = 3;
constexpr int max = math::Max( a, b );

I get this error:

error C3245: 'math::Max': use of a variable template requires template argument list

What is the best way in modern C to do this correctly?

CodePudding user response:

One possible solution is to introduce a function object:

struct Max_ {
    template<class T>
    constexpr T operator()(const T& a, const T& b) const {
        return std::max(a, b);
    }
};

inline constexpr Max_ Max = {};

Then you can do

std::cout << Max(4, 5); // prints 5

CodePudding user response:

Perhaps this bleeding-edge-modern, law-abiding, namespace-respecting, argument-forwarding function alias construct can work for you.

#define FUNCTION_ALIAS(from, to) \
   decltype(auto) to(auto&& ... xs) \
     { return from(std::forward<decltype(xs)>(xs)...); }

FUNCTION_ALIAS(std::max, Max)
  •  Tags:  
  • c
  • Related