如何使用 SFINAE 检测 noexcept 方法 [英] How to detect a noexcept method using SFINAE
问题描述
我问的是一个(流行的)问题的变体 - 检测类的方法的存在.
I'm asking about a variation of a (popular) question - detecting the existence of a method of a class.
我在这里阅读了很多答案,大多数(C++17 后)解决方案看起来像 这个:
I've read many answers here in SO, and most of the (post C++17) solutions look like 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
是良构的,然后 decltype(std::declval<T>().foo())
不会产生编译器错误,那么编译器更喜欢" has_foo<T, typename voider<decltype(...)>>::type
因为它不需要用默认类型替换第二个模板类型.
Basically, we're letting the compiler decide using a "trick" :
if the expression std::declval<T>().foo()
is well-formed,
then decltype(std::declval<T>().foo())
doesn't produce a compiler-error,
then the compiler "prefers" has_foo<T, typename voider<decltype(...)>>::type
since it doesn't need to replace the second template type with a default type.
很好,但是我们如何将 noexcept
与它结合起来呢?我尝试了很多方法,但似乎大多数技术(包括 decltype(declval<type>.my_func())
)只关心名称、返回类型和参数类型,而不关心 noexcept.
great, but how can we combine noexcept
with it?
I've tried many ways but it seems most techniques (including decltype(declval<type>.my_func())
)
only care about the name, return type and the argument types and not about the noexcept.
推荐答案
您可以在 noexpect
运算符(C++11 起).
You can do it with the help of noexpect
operator (since C++11).
noexcept 运算符执行编译时检查,如果表达式声明为不抛出任何异常,则返回 true.
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{};
这篇关于如何使用 SFINAE 检测 noexcept 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!