Search code examples
c++c++11c++14constexprreturn-type

Warning: function uses 'auto' type specifier without trailing return type


The following code gives the warning below. Can someone please explain why (note the code is not useful as is as I replaced my types with int to make a complete example).

warning: 'MaxEventSize()' function uses 'auto' type specifier without trailing return type [enabled by default]

The idea is to get the maximum size of a particular structure (types go where int is).

template<typename T>
constexpr T cexMax(T a, T b)
{
    return (a < b) ? b : a;
}

constexpr auto MaxEventSize()
{
    return cexMax(sizeof(int),
           cexMax(sizeof(int),
                    sizeof(int)));
};

Solution

  • The auto return type "without trailing return type" is a C++14 feature, so I suppose you're compiling C++11.

    Your code is OK with C++14, but for C++11, if you want use auto as return type, you need describe the effective return type in this way (caution: pseudocode)

    auto funcName (args...) -> returnType
    

    You know that sizeof() returns std::size_t, so your example can be corrected as

    constexpr auto MaxEventSize() -> std::size_t
    {
        return cexMax(sizeof(int),
               cexMax(sizeof(int),
                        sizeof(int)));
    };
    

    or (silly, in this case, but show the use in more complex examples)

    constexpr auto MaxEventSize() -> decltype( cexMax(sizeof(int),
                                                      cexMax(sizeof(int),
                                                             sizeof(int))) )
    {
        return cexMax(sizeof(int),
               cexMax(sizeof(int),
                        sizeof(int)));
    };