Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom literal works with long double but not double, and with pass by value but not pass by reference

I'm experimenting with C++ custom literals. I'm finding it strange that the simple function below stops working when I change the type from long double type to double, or when try to pass by reference.

At first I thought it had to do with the use of constexpr but that does not seem to be the case, as both of these work fine if it's not on an operator "", and removing the constexpr from the operator "" does not remove the error.

Are these well-thought-out decisions in the design of the language, or just nuances that my compiler (gcc 4.8.2) can't deal with?

// Conversion function, works fine with both long double and
// double, and with or without pass by reference.
constexpr long double to_deg (const long double& deg)
{
    return deg*M_PI/180.0;
}

// Custom literal with long double types and pass by value,
// works fine.
constexpr long double operator "" _deg (long double deg)
{
    return deg*M_PI/180.0;
}

// Custom literal with double types, gives "Invalid argument list."
// error.
constexpr double operator "" _deg (double deg)
{
    return deg*M_PI/180.0;
}

// Custom literal with pass by reference, gives "Invalid argument list." 
// error. Removing the const does not remove the error.
constexpr long double operator "" _deg (const long double& deg)
{
    return deg*M_PI/180.0;
}
like image 665
MGA Avatar asked Jul 25 '14 13:07

MGA


1 Answers

The C++ Standard, section § 13.5.8 ( User-defined literals), lists all the valid types :

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

Neither double or double& , const long double& are listed here : so they are not allowed.

like image 112
quantdev Avatar answered Oct 14 '22 00:10

quantdev