【发布时间】: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<T>().foo() 格式正确,
那么decltype(std::declval<T>().foo()) 不会产生编译器错误,
然后编译器“首选”has_foo<T, typename voider<decltype(...)>>::type,因为它不需要用默认类型替换第二个模板类型。
很好,但是我们如何将noexcept 与它结合起来呢?
我尝试了很多方法,但似乎大多数技术(包括decltype(declval<type>.my_func()))
只关心名称、返回类型和参数类型,而不关心 noexcept。
【问题讨论】:
-
那么为什么不直接使用
noexcept运算符呢?
标签: c++ templates methods sfinae noexcept