代码之家  ›  专栏  ›  技术社区  ›  olist

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

  •  5
  • olist  · 技术社区  · 7 年前
    // 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;
    }
    

    以下是编译输出:

    错误:聚合 ‘td<int> t1’ 类型不完整,无法定义
    错误:聚合 ‘td<const int> t2’ 类型不完整,无法定义

    那么,为什么 decltype((const int)a) decltype((const int)1) 不同?

    2 回复  |  直到 7 年前
        1
  •  5
  •   M.M    7 年前

    说明符 decltype((const int)a) decltype((const int)1) 双方都决心 int . 这是因为没有 const 非类类型的PR值,如C++ 17中所包含的[EXPR]:

    如果prvalue最初具有类型 cv T ,在哪里 T 是cv非限定非类、非数组类型,表达式的类型调整为 T 在进一步分析之前。

    您的输出可能只是诊断消息中的一个错误。要确认编译器错误,您可以编写一些行为因decltype结果而异的代码,例如:

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

    应该编译成功。

        2
  •  3
  •   Cheers and hth. - Alf    7 年前

    不是答案,只是附加数据。

    以下代码,

    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;
    }
    

    用Visual C++ 2017编译干净,但不使用明文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]
    > _
    

    这表示存在g++编译器错误。