我正在问一个(受欢迎的)问题的变体-检测类方法的存在。
我已经在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起)。
noexpect