c++c++11user-defined-literals

Why do I have to use long double for user defined literals?


The following user defined literal emits an error:

constexpr double operator "" _kg(double q)
{
   return q*1000;
}

but if long is added the error will disappear and the code will work as follows:

constexpr double operator "" _kg(long double q)
{
   return q*1000;
}

the error is:

‘constexpr double operator""_kg(double)’ has invalid argument list

The problem is only caused by the argument and the return type can be double without long.

Why is long needed?


Solution

  • C++11 draft n3290 has this to say about the parameters that user-defined literals can take (§13.5.8):

    The declaration of a literal operator shall have a parameter-declaration-clause equivalent to one of the following:

    const char*
    unsigned long long int
    long double
    char
    wchar_t
    char16_t
    char32_t
    const char*, std::size_t
    const wchar_t*, std::size_t
    const char16_t*, std::size_t
    const char32_t*, std::size_t
    

    As you can see, double is not in that list, only long double is. So you have to use that for user-defined literals that expect a floating point number as an argument.