当从函数作为"const"返回时,为什么原始类型和用户定义类型的行为不同? [英] Why do primitive and user-defined types act differently when returned as 'const' from a function?
问题描述
#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 ++会区别对待内置类型和自定义类型?
我没有该标准的引用,但 The issue description is embedded in the code. My compiler is I just wonder: Why does C++ treat built-in types and custom types differently in such a case? I don't have a quote from the standard, but cppreference confirms my suspicions: 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.) The returned 这篇关于当从函数作为"const"返回时,为什么原始类型和用户定义类型的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!clang 5.0
.
const int
is just a normal int
prvalue, and makes the non-const overload a better match than the const
one.