【发布时间】:2013-08-29 04:18:03
【问题描述】:
作为一般规则,decltype 保留常量:
const int ci = 0;
decltype(ci) x; // x is const int
x = 5; // error--x is const
class Gadget{}:
const Gadget makeCG(); // factory
decltype(makeCG()) y1, y2; // y1 and y2 are const Gadgets
y1 = y2; // error--y1 is const
但是对于返回基本类型的 const 返回类型,decltype 似乎将 const 扔掉了:
const int makeCI(); // factory
decltype(makeCI()) z; // z is NOT const
z = 5; // okay
为什么decltype 在这种情况下会丢弃常量?我的意思有两个方面:
- 标准的哪一部分规定了这种行为?
- 以这种方式指定行为的动机是什么?
谢谢。
【问题讨论】:
-
为什么要通过 const 值返回?
-
@BillyONeal:一个很好的问题,但这并不会使这个问题无效。
-
@NicolBolas:我从未声称它确实如此。
-
@BillyONeal:我的兴趣在于理解 decltype,因为它对用户定义类型和基本类型以不同的方式处理返回值,我只是想知道为什么。