Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use type traits to check whether a type is a container?

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.

like image 440
Nordlöw Avatar asked Oct 01 '11 00:10

Nordlöw


1 Answers

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.

like image 158
Jared Hoberock Avatar answered Nov 15 '22 10:11

Jared Hoberock