c++variadic-templatesfold-expression

C++ fold expressions, how to apply it with a function instead of an operator?


I have a set of messages, some of which have variable sizes but still with fixed maximum sizes. I want to get the maximum size amongst that set of messages.

template< typename... Messages >
struct BinaryMessageList
{
    static constexpr size_t maxSize()
    {
        return (std::max(Messages::maxSize(), ...));
    }
};

So the point is to compute the same as std::max(M1::sizeMax(), ..., Mn::sizeMax()). I tried the multi arguments version of std::max or the usual binary version of std::max but I fail to compile that code. I know how to do so with operators but I'm unsure how it can be achieved through functions.

EDIT: I was redirected to Fold expressions with arbitrary callable? but my question is not how to write a variadic max function but how to apply std::max to values of calls to variadic constexpr-ed Class::maxSize().


Solution

  • std::max has an overload that accepts an initializer_list, so you can:

    #include <algorithm>
    
    template<typename... Messages>
    struct BinaryMessageList
    {
        static constexpr size_t maxSize()
        {
            return std::max({size_t(Messages::maxSize())...});
        }
    };