开发者

How to determine if a class contains a subclass / type?

开发者 https://www.devze.com 2023-03-16 14:51 出处:网络
Can we have a SFINAE trick to know, if the class has certain subclass/type. Something like, template<typename TYPE> // searches for \"my_type\"

Can we have a SFINAE trick to know, if the class has certain subclass/type. Something like,

template<typename TYPE> // searches for "my_type"
struct has_inner_type {
  enum { value = <???> };
};

Following are the examples:

struct A {
  class my_type {};  // has_inner_type::value = true 
};
struct B { }; // has_inner_type::value = false
struct C { typedef int my_type; }; // has_inner_type::value = true

I tried few tricks, but falling short mostly with expected compiler errors. Usage:

bool b = has_inner_type<A>::value;  // with respect to "my_type"

Edit: I have re-edited my question, as it seems that it's impossible to pass my_typ开发者_StackOverflow社区e as second parameter to has_inner_type. So, as of now the question is to find only a specific type as my_type. I have tried this code, which doesn't work.


Following is the answer which was present in the wikipedia link I posted in the question !! (thanks to @n.m.)

template <typename T> 
struct has_inner_type
{
  typedef char yes[1];
  typedef char no[2];

  template <typename C> static yes& test(typename C::my_type*);
  template <typename> static no& test(...);

  static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};

Here is the demo.

0

精彩评论

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