c++templatesconstexprnumeric-limits

How to generalize concept with templated function?


Given something like the following:

struct numeric_limits_max_t {
   template<class T>
   constexpr operator T() const noexcept {
      return std::numeric_limits<T>::max();
   }
};

constexpr numeric_limits_max_t numeric_limits_max; // can be used to automaticly construct maximum value in eg. function calls

How can this concept be generalized into something like (pseudocode) ?

constexpr implicit_convert_t numeric_limits_max{std::numeric_limits<???>::max()};

So the problem becomes when trying to make this into a generalized template/concept:

template<class F>
struct implicit_convert_t {
   F f;

   template<class T>
   constexpr operator T() const noexcept {
      return f<T>(); /// <--- what do: this doesn't work/compile
   }
};

constexpr implicit_convert_t numeric_limits_max{std::numeric_limits<???>::max()};

Can this be solved?


Solution

  • Make the data member a function template so it can be instantiated at the call site.

    template<class F>
    struct implicit_convert_t {
       F f;
    
       template<class T>
       constexpr operator T() const noexcept {
          return f.template operator()<T>();
       }
    };
    
    constexpr implicit_convert_t numeric_limits_max{[]<typename T>() { return std::numeric_limits<T>::max(); }};