我正在尝试使用 C++ 自定义文字。当我将类型从long double
type 更改为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;
}