After seeing many examples of metaprogramming in C++ that allow for figuring out may properties of classes (such as knowing if a type is a specialization of a template ), or knowing if a class incorporates a given nested type; but I was wondering if is was possible to write a test or trait that determines the inverse of the last one - to check if a given Type
is nested within a class
or struct
.
In other words, I'm looking for the equivalent of the following pseudocode:
template <typename Type> struct is_nested {
enum { value = {__some magic__} };
};
typedef int type1;
struct Something { typedef int internal_type; };
typedef Something::internal_type type2;
//...later, likely at a different scope
is_nested< int >::value; // yields false
is_nested< std::vector<int>::iterator >::value; // yields true
is_nested< type1 >::value; // yields false
is_nested< type2 >::value; // yields true
I know I can use sizeof
to implement yes/no tests, and I presume Type
is part of those tests, but I can't figure out how to plug in some sort of "any viable type" into the test such that I can form an expression like Anytype::Type
.
template struct is_nested { typedef char yes; typedef struct { char u[2]; } no; // Herein lies the problem ???? static yes test( char [ sizeof(Anytype::Type) ] ) ; ???? static no test(...); public: enum { value = sizeof(test(0)) == sizeof(char) }; };
(Note that I don't care nor (can afford to) know what type would Type
be nested in; all it matters is if it is nested in something or not. In other words, this trait should only depend on Type
.)
I'm looking for a C++ solution be it in C++11 or C++03, but in the first case I would welcome it much more if it was backportable.