我问的是一个(流行)问题的变体 - 检测类方法的存在。
我在 SO 中读过很多答案,大多数(C++17 后)解决方案看起来像this https://stackoverflow.com/questions/55191505/c-compile-time-check-if-method-exists-in-template-type:
#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操作员 https://en.cppreference.com/w/cpp/language/noexcept(自 C++11 起)。
noexcept 运算符执行编译时检查,如果声明表达式不引发任何异常,则返回 true。
e.g.
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 https://wandbox.org/permlink/lXuw9NNmAlM2uht7
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)