C++ STL 容器不允许实例化不完整的类型;这是未定义的行为。
这是绕过该限制的有效“技巧”吗?还是这个技巧仍然有未定义的行为?
#include <vector>
template<template<class, class> class Vector = std::vector>
struct my_incomplete_vector
{
struct Element;
// Element is incomplete here, but does it matter anymore?
typedef Vector<Element, std::allocator<Element> > type;
struct Element { typename type::iterator value; };
};
int main()
{
my_incomplete_vector<>::type v;
v.resize(1);
// this isn't normally possible without incomplete types
v[0].value = v.begin();
return 0;
}
最佳答案
这是未定义的行为。该标准要求一个类型是
如果它被用作模板的参数,则完成
实例化模板的点。和
my_incomplete_vector::Element
使用时不完整
在 Element
中。没有问题不会发生,直到你真正
当然,实例化您的模板,但是 g++ 无法编译
您的代码与通常的调试选项
(-D_GLIBCXX_CONCEPT_CHECKS -D_GLIBCXX_DEBUG
-D_GLIBCXX_DEBUG_PEDANTIC
).
关于c++ - 允许模板中不完整类型的技巧?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19033970/