3

如果该类具有某些子类/类型,我们能否知道一个SFINAE技巧。就像是,

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

以下是示例:

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

我尝试了一些技巧,但主要是由于预期的编译器错误而失败。用法:

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

编辑:我重新编辑了我的问题,因为它似乎不可能my_type作为第二个参数传递给has_inner_type. 所以,到目前为止,问题是只找到一个特定类型作为my_type. 我已经尝试过这段代码,它不起作用。

4

1 回答 1

0

以下是我在问题中发布的维基百科链接中的答案!(感谢@nm。)

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);
};

这是演示

于 2011-07-02T04:05:13.790 回答