Question

Can I use C++ Type Traits to check if a type is an STL-like container? I already know of GCC's builtin __is_class but I would like to be a bit more specific if possible.

Was it helpful?

Solution

You could build your own traits classes to check a type for the Container interface. This would involve validating that certain associated types (such as container::iterator) exist and validating that certain expressions (such as container.empty()) are valid (i.e., they compile without error). Various SFINAE techniques can be used to build traits classes which check for nested types and validate expressions.

SGI's page specifies in detail the associated types and valid expressions that types which model the Container "concept" must provide. The most recent ISO C++ standard document would probably provide a more authoritative source since the SGI page is pretty old.

Of course, traits classes can't validate the semantics of expressions like container.empty(); they can only check that the expressions are legal. Some have proposed extending the language to allow the programmer to assert the semantic properties of expressions, which would address this limitation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top