gpt4 book ai didi

c++ - T 是否必须是完整类型才能在 `std::declval` 中使用?

转载 作者:行者123 更新时间:2023-12-02 02:36:52 25 4
gpt4 key购买 nike

考虑这个例子(来自 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 不完整。铿锵错误是:

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;
~~~^

最佳答案

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

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

For the first option (dot) the first expression shall have complete class type.

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

For the first option (dot) the first expression shall be a glvalue having complete class type.

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

A class is considered a completely-defined object type ([basic.types]) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments, noexcept-specifiers, and default member initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

关于c++ - T 是否必须是完整类型才能在 `std::declval<T>` 中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59268030/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com