What is decltype(0 + 0)?

落花浮王杯 提交于 2019-12-01 15:14:42

From 5.19 [expr.const], every literal constant expression is a prvalue.

A literal constant expression is a prvalue core constant expression of literal type, but not pointer type. An integral constant expression is a literal constant expression of integral or unscoped enumeration type.

Therefore rule 4 applies to all literal constant expressions.

0 + 0 is an expression of two prvalues, (n3290 par. 3.10) which applies the built-in operator+, which, per 13.6/12 is LR operator+(L,R), which is therefore a function that returns something that is not a reference. The result of the expression is therefore also a prvalue (as per 3.10).

Hence, the result of 0 + 0 is a prvalue, 0 is an int, therefore the result of 0 + 0 is an int

It is definitely an int:

#include <iostream>
#include <typeinfo>

template<typename T>
struct ref_depth
{
        enum { value = 0 };
};

template<typename T>
struct ref_depth<T&>
{
        enum { value = 1 };
};

template<typename T>
struct ref_depth<T&&>
{
        enum { value = 2 };
};

int main() {

  std::cout
    << "int: " << typeid(int).name() << "\n"
       "decltype(0 + 0): " << typeid(decltype(0 + 0)).name() << "\n"
       "int&&: " << typeid(int&&).name() << "\n";
  std::cout 
    << "ref_depth: int: " << ref_depth<int>::value << "\n"
       "ref_depth: decltype(0 + 0): " << ref_depth<decltype(0 + 0)>::value << "\n"
       "ref_depth: int&&: " << ref_depth<int&&>::value << "\n";

}

Output:

int: i
decltype(0 + 0): i
int&&: i
ref_depth: int: 0
ref_depth: decltype(0 + 0): 0
ref_depth: int&&: 2

Your reasoning is correct. An expression involving only constants is a constant by itself. Thus

decltype(0 + 0) x;

equals

decltype(0) x;

which equals

int x;

GCC says int-

Code:

#include <iostream>
#include <typeinfo>

int
main ()
{
  int n;
  decltype(0 + 0) x;
  std::cout << "Type of `n': " << typeid(n).name() << std::endl;
  std::cout << "Type of `x': " << typeid(x).name() << std::endl;
}

Output:

i

i

Edit: It makes sense according to point 4, but I can't say for sure that point 2 isn't actually the one in effect. From what I can tell, 0 + 0 is evaluated to 0, and the type of 0 is int, so that is the declared type.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!