简体   繁体   中英

Member detection based on custom void_t implementation

I've got the book C++ Templates the complete guide and I'm trying to implement some of the described techniques. One of these is member function detection, but my implementation seems not working.

I can't use void_t as I'm using C++11, but I copied the definition, so this should be not the problem.

Following is the code:

namespace nt_detail
  {
  template< class... >
  using void_t = void;
  }

template<typename T, typename = nt_detail::void_t<>>
struct HasHelloMember
    : std::false_type {};

template<typename T>
struct HasHelloMember<T,
    nt_detail::void_t<decltype(std::declval<T>().hello())>>
       : std::true_type {};

and here the test one:

class ZZZ
  {

  };

class ZZZ2
  {
  public:
  void hello()
    {}
  };

int main()
  {
  if(HasHelloMember<ZZZ>::value)
    {
    std::cout << "ZZZ has hello" << std::endl;
    }
  else
    {
    std::cout << "ZZZ has NOT hello" << std::endl;
    }



if(HasHelloMember<ZZZ2>::value)
  {
  std::cout << "ZZZ2 has hello" << std::endl;
  }
else
  {
  std::cout << "ZZZ2 has NOT hello" << std::endl;
  }
}

In both cases I get "has hello". Is there something wrong with my void_t implementation perhaps?

Try this definition of void_t unless You are using C++17:

template<typename... Ts> struct make_void { typedef void type;};
template<typename... Ts> using void_t = typename make_void<Ts...>::type;

According to https://en.cppreference.com/w/cpp/types/void_t :

Until CWG 1558 (a C++14 defect), unused parameters in alias templates were not guaranteed to ensure SFINAE and could be ignored, so earlier compilers require a more complex definition of void_t, such as

This is an issue with gcc until version 5.1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM