5

我正在尝试使用 C++ 自定义文字。当我将类型从long doubletype 更改为double或尝试通过引用传递时,我发现下面的简单函数停止工作很奇怪。

起初我认为它与使用有关,constexpr但情况似乎并非如此,因为如果它不在 an 上,这两个都可以正常工作operator "",并且constexpr从 theoperator ""中删除并不会消除错误。

这些是语言设计中经过深思熟虑的决定,还是我的编译器(gcc 4.8.2)无法处理的细微差别?

// 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;
}
4

1 回答 1

5

C++ 标准第 13.5.8 节(用户定义的文字)列出了所有有效类型:

文字运算符的声明应具有等效于以下之一的参数声明子句:

  • 常量字符*
  • unsigned long long int
  • 长双
  • 字符
  • wchar_t
  • char16_t
  • char32_t
  • const char*, std::size_t
  • 常量 wchar_t*, std::size_t
  • 常量 char16_t*, std::size_t
  • 常量 char32_t*, std::size_t

doubledouble&,均未const long double&在此处列出:因此不允许使用。

于 2014-07-25T13:47:20.693 回答