c++ - 如何使用SFINAE检测noexcept方法

标签 c++ templates methods sfinae noexcept

我在问一个(受欢迎的)问题的变体-检测类方法的存在。

我已经在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/

相关文章:

c++ - placement new 如何知道要创建哪个布局?

c++ - boost 共享指针 : Simultaneous Read Access Across Multiple Threads

c++ - 在 C++ Vector 中存储从类模板继承的类

java - 我的方法应该迭代很多次但不是,为什么?

iOS Objective C 方法问题

Java 方法运行后不打印任何内容

c++ - 需要读取文本文件 C++ 中某些字符之间的文本

c++ - 在常量表达式中使用 numeric_limits::max()

c++ - 结合 Eigen 和 CppAD

java - 泛型方法中参数的构造函数(java)