Does T have to be a complete type to be used in `std::declval<T>`?

こ雲淡風輕ζ 提交于 2020-01-03 07:59:10

问题


Consider this example (coming from 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;
}

It compiles with no errors on gcc9.2 but gcc7.2 and clang 10.0.0 complain about B not being complete. Clangs error is:

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

回答1:


The source of the error is not std::declval, but incomplete class member access.

Until the resolution of CWG1836 was merged 2.5 years ago, the standard required the class to be complete in a class member access expression (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.

And a class is not regarded as complete in alias-declaration within its own 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.




回答2:


From [declval]:

Remarks: The template parameter T of declval may be an incomplete type.

This wording has been present since C++11 (so it's not possible for compilers to be conforming to an earlier standard)



来源:https://stackoverflow.com/questions/59268030/does-t-have-to-be-a-complete-type-to-be-used-in-stddeclvalt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!