当从函数作为"const"返回时,为什么原始类型和用户定义类型的行为不同? [英] Why do primitive and user-defined types act differently when returned as 'const' from a function?

查看:98
本文介绍了当从函数作为"const"返回时,为什么原始类型和用户定义类型的行为不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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 clang 5.0.

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 int is just a normal int prvalue, and makes the non-const overload a better match than the const one.

这篇关于当从函数作为"const"返回时,为什么原始类型和用户定义类型的行为不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆