简体   繁体   English

不同类型的`decltype((const int)a)`和`decltype((const int)1)`

[英]Different types of `decltype((const int)a)` and `decltype((const int)1)`

// g++ 7.3
template<typename T>
struct td;

int main()
{
  int a = 1;

  td<decltype((const int)a)> t1;
  td<decltype((const int)1)> t2;

  return 0;
}

Below is the output of compilation: 下面是编译的输出:

error: aggregate 'td<int> t1' has incomplete type and cannot be defined 错误:聚合'td<int> t1'类型不完整,无法定义
error: aggregate 'td<const int> t2' has incomplete type and cannot be defined 错误:聚合'td<const int> t2'类型不完整,无法定义

So, why are the types of decltype((const int)a) and decltype((const int)1) different? 那么,为什么decltype((const int)a)decltype((const int)1)不同?

The specifiers decltype((const int)a) and decltype((const int)1) both resolve to int . 说明符decltype((const int)a)decltype((const int)1)都解析为int This is because there are no const prvalues of non-class type, as covered in C++17 [expr]: 这是因为没有非类型的const prvalues,如C ++ 17 [expr]中所述:

If a prvalue initially has the type cv T , where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis. 如果prvalue最初具有类型cv T ,其中T是cv非限定的非类非数组类型,则在进行任何进一步分析之前将表达式的类型调整为T

Your output might just be a bug in the diagnostic message. 您的输出可能只是诊断消息中的错误。 To confirm a compiler bug you could write some code whose behaviour differs depending on the decltype result, eg: 要确认编译器错误,您可以编写一些代码,其行为因decltype结果而异,例如:

decltype((const int)1) x;  x = 5;

which should compile successfully. 哪个应该编译成功。

Not an answer, just additional data. 不是答案,只是额外的数据。

The following code, 以下代码,

template< class Type > struct T{ Type x; };

int main()
{
    int a = 1;
    T<decltype((const int)a)> t1; t1.x = 1;
    T<decltype((const int)1)> t2; t2.x = 2;
}

… compiles cleanly with Visual C++ 2017, but not with MinGW g++ 7.2.0: ...使用Visual C ++ 2017进行干净编译,但不能使用MinGW g ++ 7.2.0进行编译:

[P:\temp]
> g++ foo.cpp
foo.cpp: In function 'int main()':
foo.cpp:7:31: error: use of deleted function 'T<const int>::T()'
     T<decltype((const int)1)> t2; t2.x = 2;
                               ^~
foo.cpp:1:31: note: 'T<const int>::T()' is implicitly deleted because the default definition would be ill-formed:
 template< class Type > struct T{ Type x; };
                               ^
foo.cpp:1:31: error: uninitialized const member in 'struct T<const int>'
foo.cpp:1:39: note: 'const int T<const int>::x' should be initialized
 template< class Type > struct T{ Type x; };
                                       ^
foo.cpp:7:42: error: assignment of read-only member 'T<const int>::x'
     T<decltype((const int)1)> t2; t2.x = 2;
                                          ^

[P:\temp]
> _

This indicates a g++ compiler bug. 这表示g ++编译器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM