3

I'm asking about a variation of a (popular) question - detecting the existence of a method of a class.

I've read many answers here in SO, and most of the (post C++17) solutions look like this:

#include <type_traits>

template<class ...Ts>
struct voider{
    using type = void;
};

template<class T, class = void>
struct has_foo : std::false_type{};

template<class T>
struct has_foo<T, typename voider<decltype(std::declval<T>().foo())>::type> : std::true_type{};

Basically, we're letting the compiler decide using a "trick" : if the expression std::declval<T>().foo() is well-formed, then decltype(std::declval<T>().foo()) doesn't produce a compiler-error, then the compiler "prefers" has_foo<T, typename voider<decltype(...)>>::type since it doesn't need to replace the second template type with a default type.

great, but how can we combine noexcept with it? I've tried many ways but it seems most techniques (including decltype(declval<type>.my_func())) only care about the name, return type and the argument types and not about the noexcept.

David Haim
  • 25,446
  • 3
  • 44
  • 78

1 Answers1

4

You can do it with the help of noexpect operator (since C++11).

The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions.

e.g.

template<class T>
struct has_foo<T, 
               typename voider<decltype(std::declval<T>().foo()),
                               std::enable_if_t<noexcept(std::declval<T>().foo())>
                              >::type
              > : std::true_type{};

LIVE

songyuanyao
  • 169,198
  • 16
  • 310
  • 405