c++ - 自定义文字适用于 long double 但不适用于 double,并且适用于按值传递但不按引用传递

标签 c++ c++11 literals constexpr user-defined-literals

我正在试验 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

doubledouble&const long double& 均未在此处列出:因此它们是不允许的。

关于c++ - 自定义文字适用于 long double 但不适用于 double,并且适用于按值传递但不按引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24956922/

相关文章:

multithreading - gcc 支持 unique_locks 吗?

c++ - 使用 lambda 迭代 std::vector 不想使用 remove_if 删除

Javascript 对象字面量 - 调用

java - 为什么 Java SE 1.7 中数字文字中的下划线规则在八进制和十六进制中不同?八进制文字不是违反规则吗?

c - 将一个文字定义为另一个文字的倍数会导致错误的结果

C++ 信号和访问 QtQuick 项

c++ - 如何做出健壮的断言?

c++ - 如何检测流中的 CRLF

c++ - 为什么 Qt 在信号和槽中抛出 lambda 表达式错误?

c++ - 自定义异常层次结构。来自 std::exception 和 std::bad_alloc 的可怕钻石