【问题标题】:How to detect a noexcept method using SFINAE如何使用 SFINAE 检测 noexcept 方法
【发布时间】:2020-05-11 12:06:03
【问题描述】:

我在问一个(流行的)问题的变体——检测一个类的方法是否存在。

我在 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&lt;T&gt;().foo() 格式正确, 那么decltype(std::declval&lt;T&gt;().foo()) 不会产生编译器错误, 然后编译器“首选”has_foo&lt;T, typename voider&lt;decltype(...)&gt;&gt;::type,因为它不需要用默认类型替换第二个模板类型。

很好,但是我们如何将noexcept 与它结合起来呢? 我尝试了很多方法,但似乎大多数技术(包括decltype(declval&lt;type&gt;.my_func())) 只关心名称、返回类型和参数类型,而不关心 noexcept。

【问题讨论】:

  • 那么为什么不直接使用noexcept 运算符呢?

标签: c++ templates methods sfinae noexcept


【解决方案1】:

您可以在noexpect operator 的帮助下完成此操作(C++11 起)。

noexcept 运算符执行编译时检查,如果声明表达式不抛出任何异常,则返回 true。

例如

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 2018-02-02
    • 2016-02-13
    • 2012-05-29
    相关资源
    最近更新 更多