It's undefined behavior. The standard requires a type to be
complete if it is used as the argument of a template, at the
point where the template is instantiated. And
my_incomplete_vector::Element
is not complete when you use it
inside Element
. No problems will occur until you actually
instantiate your template, of course, but g++ fails to compile
your code with the usual debugging options
(-D_GLIBCXX_CONCEPT_CHECKS -D_GLIBCXX_DEBUG
-D_GLIBCXX_DEBUG_PEDANTIC
).
Trick to allow incomplete types in templates?
-
29-06-2022 - |
Question
C++ STL containers don't allow instantiation with incomplete types; it is undefined behavior.
Is this a valid "trick" to get around that restriction? Or does this trick still have undefined behavior?
#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;
}
La solution
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow