我正在试验 C++ 自定义文字。当我将类型从 long double
类型更改为 double
或尝试通过引用传递时,我发现下面的简单函数停止工作很奇怪。
起初我认为它与 constexpr
的使用有关,但事实似乎并非如此,因为如果它不在 operator ""上,这两种方法都可以正常工作
,并且从 operator ""
中删除 constexpr
不会删除错误。
这些是语言设计中经过深思熟虑的决定,还是我的编译器 (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;
}
最佳答案
C++ 标准第 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
double
或 double&
、const long double&
均未在此处列出:因此它们是不允许的。
关于c++ - 自定义文字适用于 long double 但不适用于 double,并且适用于按值传递但不按引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24956922/