c++ - 为什么从函数返回 'const' 时,原始类型和用户定义类型的行为不同?

标签 c++ c++11 overloading standards overload-resolution

#include <iostream>

using namespace std;

template<typename T>
void f(T&&) { cout << "f(T&&)" << endl; }

template<typename T>
void f(const T&&) { cout << "f(const T&&)" << endl; }

struct A {};
const A g1() { return {}; }
const int g2() { return {}; }

int main()
{
    f(g1()); // outputs "f(const T&&)" as expected.
    f(g2()); // outputs "f(T&&)" not as expected.
}

问题描述嵌入在代码中。我的编译器是 clang 5.0

我只是想知道:

在这种情况下,为什么 C++ 会以不同的方式对待内置类型和自定义类型?

最佳答案

我没有标准的引用,但是 cppreference证实了我的怀疑:

A non-class non-array prvalue cannot be cv-qualified. (Note: a function call or cast expression may result in a prvalue of non-class cv-qualified type, but the cv-qualifier is immediately stripped out.)

返回的 const int 只是一个普通的 int prvalue,并且使非 const 重载比 const 更匹配。

关于c++ - 为什么从函数返回 'const' 时,原始类型和用户定义类型的行为不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43798210/

相关文章:

c++ - 运算符<< 重载解析 (C++)

c++ - 如何在不降级为基类的情况下制作*对象的 vector

c++ - 为什么 std::function 不能接受推导类型作为其模板参数?

c++ - 没有调用 for_each 的匹配函数

c++ - 读取以二进制格式存储在字符数组中的 double

c++ - std::isgraph 在使用 `using namespace std` 时不明确

c++ - MFC 静态链接未解析的外部符号

c++ - system() 在作为 CGI 调用时总是返回非零值

java - Bukkit - 为什么转换为 Damageable 有效?

scala - Scala 3 中使用 Varargs 的模糊重载