C++11:unique_ptr抱怨类型不完整,但当我包装它时却没有
C++11: unique_ptr complains about incomplete type, but not when I wrap it
关于SO上的unique_ptr和不完全类型,已经有很多问题了,但没有一个能给我一个概念来理解为什么以下不起作用:
// error: ... std::pair<...>::second has incomplete type
template<typename K, typename T> struct Impl {
typedef typename std::unordered_map<K,Impl<K,T>>::iterator iter_type;
std::unique_ptr<iter_type> ptr;
Impl() : ptr(new iter_type()) {}
};
int main() { Impl<int,int>(); return 0; }
而以下情况会发生:
template<typename K, typename T> struct Impl {
struct Wrapper {
typedef typename std::unordered_map<K,Impl<K,T>>::iterator iter_type;
iter_type iter;
};
std::unique_ptr<Wrapper> ptr;
Impl() : ptr(new Wrapper()) {}
};
int main() { Impl<int,int>(); return 0; }
我看不出技术区别在哪里:如果第一个例子中std::pair<...>::second
(即Impl<K,T>
)对Impl
不完整,那么第二个例子中它对Wrapper
也应该不完整。而且当把unique_ptr
封装在一个结构中就足够了,为什么对第一种情况有限制?
更新:
在Dietmar Kühl的回答之后,我认为问题可以归结为以下几个方面:
template<typename K, typename T> struct Impl {
typename std::unordered_map<K,Impl<K,T>>::iterator ptr;
};
与
template<typename K, typename T> struct Impl {
struct Wrapper {
typename std::unordered_map<K,Impl<K,T>>::iterator iter;
};
Wrapper *ptr;
};
第一种情况中的问题不完整类型与std::unordered_map<K, Impl<K, T>
一起使用:要确定什么是iterator
,需要在仅声明Impl
时实例化std::unordered_map<K, Impl<K, T>
的部分。std::unique_ptr<...>
与错误无关。您可以删除对iter_type
的使用,因为typedef
需要验证它是否为类型。
另一方面,当将迭代器类型的使用包装到Wrapper
中时,在构造函数实现之前不会使用此嵌套类型。当然,内联定义的函数的行为就好像类刚刚完全定义好,并且它们是在类定义之外实现的,也就是说,上面的代码相当于
template<typename K, typename T> struct Impl {
struct Wrapper {
typedef typename std::unordered_map<K,Impl<K,T>>::iterator iter_type;
iter_type iter;
};
std::unique_ptr<Wrapper> ptr;
Impl();
};
template<typename K, typename T>
Impl<K, T>::Impl() : ptr(new Impl<K, T>::Wrapper()) {}
也就是说,当需要并实例化Wrapper
的定义时,定义Impl
。
相关文章:
- 如何在c++17中制作一个模板包装器/装饰器
- std::vector的包装器,使数组的结构看起来像结构的数组
- 如何在c++迭代器类型中包装std::chrono
- 是否可以用"iostream"包装现有的TCP/OOpenSSL会话
- 用pybind11包装C++抽象类时出错
- 为左值和右值的包装器实现C++范围
- CLANG 编译器 说:变量"PTR"可能未初始化
- C结构,其指针将被包装在unique_ptr中
- 如何包装第三方DLL在R中使用
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 在类型和包装器之间reinterpret_cast是否安全<Type>?
- 将 N-arg 函数包装到另一个函数中
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 元组由 Swig 生成的 Python 包装器返回,用于C++向量
- 包装一个对象并假装它是一个 int
- 使用 Python Extension API 包装复杂C++类
- OpenCL enqueueWriteImage no const void* ptr 在包装器中C++但在 C 函数中
- 如何创建 std::string 包装器,它将 ptr 保留为 std::string 和 ptr 到创建该包装器实例的
- c++中新建和删除ptr包装器类
- 如何使用c++ Mat类ptr对象的基本C包装器打印Mat元素?