#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/