【发布时间】: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) 说明类成员访问:“对于第一个选项(点),第一个表达式应具有完整的类类型”。而
B在alias-declaration中既不完整也不被认为是完整的。 -
@LanguageLawyer 我没找到你引用的那句话,只有"The class type shall be complete unless the class member access appears in the definition of that class"
-
@LanguageLawyer 好的,那么我同意我的解释是错误的,而且自 c++11 以来似乎发生了一些变化,这使得上述内容在较新的标准中可以,但在 c++11 中则不行。你介意写一个答案吗?
标签: c++ language-lawyer incomplete-type declval