On Thursday, 6 August 2020 at 00:58:39 UTC, Per Nordlöw wrote:
Is it possible to implement

template maxSizeOf(T...)
{
    static if (T.length == 1)
        enum size_t maxSizeOf = T[0].sizeof;
    else
    {
        enum size_t firstSize = T[0].sizeof;
        enum size_t maxSizeRest = maxSizeOf!(T[1 .. $]);
enum size_t maxSizeOf = firstSize >= maxSizeRest ? firstSize : maxSizeRest;
    }
}

in a non-recursive way?

Of course. In fact, it's trivial:

------
template maxSizeOf(T...)
{
        align(1) union Impl {
                T t;
        }
        enum maxSizeOf = Impl.sizeof;
}
------

To check that this does what we expect:
------
pragma(msg, maxSizeOf!(char)); // 1LU
pragma(msg, maxSizeOf!(char, short, ubyte)); // 2LU
pragma(msg, maxSizeOf!(char, long, ubyte)); // 8LU

align(1) struct S {
        long l;
        ubyte b;
}
pragma(msg, maxSizeOf!(long, S)); // 9LU
pragma(msg, maxSizeOf!(int, ubyte[7])); // 7LU
pragma(msg, maxSizeOf!(int, ubyte[3])); // 4LU
------

Why bother with recursion and all of that fancy gobbledygook when the compiler already knows how to compute the maximum size of something? ;-)

Reply via email to