Why Does C Prohibit Templates with Incomplete Types?
C containers, such as those in the Standard C Library, do not permit incomplete types as template parameters. This restriction arises from historical reasons.
Historical Rationale
Initially, it was thought that containers could support incomplete types. However, testing revealed inconsistencies across STL implementations. The standardization committee thus declared it undefined behavior for STL containers to work with incomplete types, extending this prohibition to the entire standard library.
This decision aimed to prevent the invalidation of existing library implementations by forcing them to support incomplete types retroactively.
Understanding the Prohibition
The committee's concern stemmed from the potential for undefined behavior and the need to maintain backward compatibility. Incomplete types in templates introduce uncertainties regarding memory management and code stability.
Future Considerations
Despite the current prohibition, Matt Austern, chair of the C library working group, predicted that future C revisions might relax the restriction on incomplete types. This could reflect a gradual shift towards increased support for incomplete types, as addressed in the C 17 standard for certain containers.
Alternative Approach
Due to the continued standard prohibition, the Boost library designers opted to create their own containers that permit incomplete types. This approach avoids the limitations imposed by the standard library and allows for more flexible data structures.
The above is the detailed content of Why Can't C Templates Use Incomplete Types?. For more information, please follow other related articles on the PHP Chinese website!