1

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?

svoltron
  • 365
  • 1
  • 10

1 Answers1

1

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.

bartop
  • 9,971
  • 1
  • 23
  • 54
  • @YSC As the text writes - it may work but it is not guaranteed – bartop Sep 14 '18 at 08:02
  • thank you! it was indeed the void_t definition, now it correctly works. PS had connection problems – svoltron Sep 14 '18 at 08:58
  • 1
    Which makes it a nice answer. FYI this quirk [has been resolved in gcc5.1](https://godbolt.org/z/YL8HO0). @bartop you might add that in your answer. – YSC Sep 14 '18 at 09:12