自定义文字使用长双精度而不是双精度,以及按值传递而不是按引用传递 我正在试用C++自定义文字。我发现很奇怪,当我将类型从longdouble类型更改为double时,或者当我尝试通过引用传递时,下面的简单函数停止工作
起初我认为这与自定义文字使用长双精度而不是双精度,以及按值传递而不是按引用传递 我正在试用C++自定义文字。我发现很奇怪,当我将类型从longdouble类型更改为double时,或者当我尝试通过引用传递时,下面的简单函数停止工作,c++,c++11,literals,constexpr,user-defined-literals,C++,C++11,Literals,Constexpr,User Defined Literals,起初我认为这与constepr的使用有关,但事实似乎并非如此,因为如果它不在操作符“上,这两种方法都可以正常工作,并且从操作符“中删除constepr并不能消除错误 这些是语言设计中经过深思熟虑的决定,还是我的编译器(GCC4.8.2)无法处理的细微差别 // Conversion function, works fine with both long double and // double, and with or without pass by reference. constexpr l
constepr
的使用有关,但事实似乎并非如此,因为如果它不在操作符“
上,这两种方法都可以正常工作,并且从操作符“
中删除constepr
并不能消除错误
这些是语言设计中经过深思熟虑的决定,还是我的编译器(GCC4.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++标准,第7.5.8节(用户定义文字),列出所有有效类型:
文字运算符的声明应具有 参数声明子句,相当于以下其中一项:- 常量字符*
- 无符号长整型
- 长双人
- 煤焦
- wchar\t
- char16\u t
- char32_t
- 常量字符*,标准::大小
- 常数wchar\u t*,标准::大小
- 常量字符16,标准::大小
- 常量字符32,标准::大小
此处未列出
double
或double&
,const-long-double&
:因此它们是不允许的。因为语言中说double
作为参数无效,引用也无效。我不知道你为什么真的需要改变它。@chris我不是真的需要改变它,我只是在试验:)。好的,我找到了“only long double”规范,但是我找不到关于无引用的任何内容。标准列出了一组有效的选项。参考资料不在里面。想要更简洁的版本,你可以试试。@chris&quantdev谢谢!我不太熟悉对标准的解释,所以我没有想到,如果没有明确说明引用,就不允许这样做。我现在明白了。注意,常量180.0
的类型是double
。要使用正版long double
常量,请添加后缀L
:180.0L
。const long double
的参数列表相当于long double
的参数列表。出于任何原因,double被排除在外?