Home >Backend Development >C++ >Are Incomplete Types Legitimate Arguments for Standard Container Instantiation?
Can Incomplete Types Enhance Standard Containers?
In the pursuit of recursive data structures, developers often resort to instantiating standard containers with incomplete types. However, the legality of such constructs has been debated due to the Standard's limited guidance on using incomplete template arguments.
The concern stems from a passage in §17.6.4.8 [lib.res.on.functions], where the Standard prohibits incomplete types as template arguments when instantiating template components, unless explicitly allowed for that component. This raises questions about the validity of constructs like:
<code class="cpp">struct multi_tree_node { std::vector< multi_tree_node & > child; };</code>
While such constructs often function seamlessly in practice, the Standard's silence on incomplete type instantiation has cast doubt upon their legality.
However, further scrutiny reveals that the Standard's restriction on incomplete types primarily applies to "operations on types...," which in the context of §17.6.4.8, refers to functions. Since instantiating a container does not involve executing any functions within its member definitions, the instantiation itself may not violate the Standard's prohibition.
This interpretation is supported by the existence of std::unique_ptr, which explicitly allows incomplete type arguments even in block scope. Additionally, the Standard's rationale behind prohibiting incomplete type instantiation, as it pertains to the efficient implementation of optimization techniques like "small vector," is not applicable to container instantiation.
Therefore, while the Standard discourages using incomplete types as arguments when instantiating template components, the legality of instantiating standard containers with incomplete types remains ambiguous. However, until further clarification is provided by the Standard, it is advisable to exercise caution with such constructs.
The above is the detailed content of Are Incomplete Types Legitimate Arguments for Standard Container Instantiation?. For more information, please follow other related articles on the PHP Chinese website!