我在问一个(受欢迎的)问题的变体-检测类方法的存在。
我已经在SO中阅读了很多答案,并且大多数(C++ 17之后的)解决方案看起来都像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{};
基本上,我们让编译器使用“技巧”来决定:
如果
std::declval<T>().foo()
表达式格式正确,则
decltype(std::declval<T>().foo())
不会产生编译器错误,那么编译器会“首选”
has_foo<T, typename voider<decltype(...)>>::type
,因为它不需要用默认类型替换第二个模板类型。很好,但是如何将
noexcept
与之结合呢?我尝试了很多方法,但似乎大多数技术(包括
decltype(declval<type>.my_func())
)只关心名称,返回类型和参数类型,而不关心noexcept。
最佳答案
您可以在 noexpect
operator(自C++ 11起)的帮助下进行操作。
The noexcept operator performs a compile-time check that returns true if an expression is declared to not throw any exceptions.
例如
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
关于c++ - 如何使用SFINAE检测noexcept方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59908697/