gpt4 book ai didi

c++ - std::pair 提示类型不完整

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:18:44 25 4
gpt4 key购买 nike

如何编译下面的代码?

#include <type_traits>
#include <utility>

struct A;

template<typename T>
struct B{
T* p;

B& operator=(B&&);
B& operator=(T&&);
};

int main(){
//typedef B<A> type;// fine
typedef B<std::pair<A, A>> type;// error

noexcept(std::declval<type&>() = std::declval<type>());

return 0;
}

PS: Type B 模拟了 boost::recursive_wrapper ,由于同样的原因编译失败。

最佳答案

typedef 本身不是问题。写 struct foo; typedef std::pair<foo, foo> bar; 是完全合法的.问题在于

noexcept(std::declval<type&>() = std::declval<type>());

这需要编译器为operator=执行重载解析.作为重载解析的一部分,它必须从 B&& 中寻找可能的转换。至 std::pair<A, A>&& ,这需要实例化 std::pair<A,A> (§14.7.1 [temp.inst]/p6):

A class template specialization is implicitly instantiated if the class type is used in a context that requires a completely-defined object type or if the completeness of the class type might affect the semantics of the program. [ Note: In particular, if the semantics of an expression depend on the member or base class lists of a class template specialization, the class template specialization is implicitly generated. For instance, deleting a pointer to class type depends on whether or not the class declares a destructor, and conversion between pointer to class types depends on the inheritance relationship between the two classes involved. —end note ]

...并且根据 §17.6.4.8 [res.on.functions]/p2,此实例化会导致未定义的行为。

虽然编译器不需要实例化std::pair<A, A>在此上下文中,因为移动赋值运算符是完全匹配的 (§14.7.1 [temp.inst]/p7):

If the overload resolution process can determine the correct function to call without instantiating a class template definition, it is unspecified whether that instantiation actually takes place.

关于c++ - std::pair 提示类型不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25925164/

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