How to detect a noexcept method using SFINAE

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-10 05:29:25

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/59908697/how-to-detect-a-noexcept-method-using-sfinae

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!