【问题标题】:Does T have to be a complete type to be used in `std::declval<T>`?T 是否必须是完整的类型才能在 `std::declval<T>` 中使用?
【发布时间】:2020-04-03 16:29:21
【问题描述】:

考虑这个例子(来自here):

#include <type_traits>
#include <iostream>
template <typename U>
struct A {
};

struct B {
   template <typename F = int>
   A<F> f() { return A<F>{}; }

   using default_return_type = decltype(std::declval<B>().f());
};

int main()
{
    B::default_return_type x{};
    std::cout << std::is_same< B::default_return_type, A<int>>::value;
}

compiles with no errors on gcc9.2 但 gcc7.2 和 clang 10.0.0 抱怨 B 不完整。 Clangs 错误是:

prog.cc:11:58: error: member access into incomplete type 'B'
   using default_return_type = decltype(std::declval<B>().f());
                                                         ^
prog.cc:7:8: note: definition of 'B' is not complete until the closing '}'
struct B {
       ^
prog.cc:16:8: error: no type named 'default_return_type' in 'B'
    B::default_return_type x{};
    ~~~^
prog.cc:17:35: error: no member named 'default_return_type' in 'B'
    std::cout << std::is_same< B::default_return_type, A<int>>::value;
                               ~~~^

【问题讨论】:

  • 问题标题似乎与错误不匹配?在我看来,GCC 似乎在抱怨 .f()。这就说得通了;不完整类型B 没有成员f
  • @MSalters 我也这么认为,但是这里真正的问题是什么?我假设一旦你从std::declval 获得了一个实例,类型是否完整就不再重要(我想我错了)
  • [expr.ref]/2 (C++11) 说明类成员访问:“对于第一个选项(点),第一个表达式应具有完整的类类型”。而Balias-declaration 中既不完整也不被认为是完整的。
  • @LanguageLawyer 好的,那么我同意我的解释是错误的,而且自 c++11 以来似乎发生了一些变化,这使得上述内容在较新的标准中可以,但在 c++11 中则不行。你介意写一个答案吗?

标签: c++ language-lawyer incomplete-type declval


【解决方案1】:

错误的来源不是std::declval,而是类成员访问不完整。

直到2.5年前CWG1836was merged的决议,标准要求类在类成员访问表达式(E1.E2)中是完整的。
[expr.ref]/2 in C++11

对于第一个选项(点),第一个表达式应具有完整的类类型。

[expr.ref]/2 in C++17:

对于第一个选项(点),第一个表达式应该是具有完整类类型的泛左值。

并且一个类在alias-declaration 中在它自己的member-specification 中不被认为是完整的。
[class.mem]/6 in C++17

类说明符的结尾}处,类被视为完全定义的对象类型([basic.types])(或完整类型)。在类 member-specification 中,该类在函数体、默认参数、noexcept-specifier 和默认成员初始化器(包括嵌套类中的此类内容)中被认为是完整的)。否则它在自己的类member-specification中被认为是不完整的。

【讨论】:

    【解决方案2】:

    来自[declval]

    备注:declval的模板参数T可能是不完整类型。

    这种措辞自 C++11 起就存在(因此编译器不可能符合早期标准)

    【讨论】:

    • 太棒了,这就是我所希望的。似乎 gcc 已经修复了,clang 还没有(还)
    • @foreknownas_463035818:我的第一个想法是T绝对应该是一个完整的类型。很高兴我检查了标准。
    猜你喜欢
    • 2011-08-26
    • 1970-01-01
    • 2016-06-02
    • 1970-01-01
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多