开发者

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

开发者 https://www.devze.com 2023-04-10 01:16 出处:网络
Can I use C++ Type Traits to check i开发者_JAVA百科f 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.You could build

Can I use C++ Type Traits to check i开发者_JAVA百科f 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号