使用 C 11 类型特征检测成员函数的存在
问题:
我们如何确定类是否拥有具有特定签名的成员函数,而不需要类提供
困境的详细阐述:
当我们需要根据类中是否存在特定成员函数来执行自定义操作时,就会出现问题。与类必须提供函数的情况不同,我们寻求一种方法来辨别其存在以进行条件处理。理想的解决方案可以避免全局函数覆盖、过多的堆栈调用和侵入式命名空间声明。
基于模板的解决方案:
利用 C 11 类型特征,我们可以设计一个验证目标是否存在的模板函数函数:
template<typename C, typename Ret, typename... Args> struct has_serialize { // Assertion to prevent instantiation with non-function arguments static_assert( std::integral_constant<T, false>::value, "Second template parameter needs to be of function type." ); // Specialization to perform the check private: template<typename T> static constexpr auto check(T*) -> typename std::is_same< decltype( std::declval<T>().serialize( std::declval<Args>()... ) ), Ret // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >::type; // attempt to call it and see if the return type is correct template<typename> static constexpr std::false_type check(...); typedef decltype(check<C>(0)) type; public: static constexpr bool value = type::value; };
用法:
我们现在可以使用 has_serialize 模板来验证类中的函数是否存在:
struct X { int serialize(const std::string&) { return 42; } }; struct Y : X {}; std::cout << has_serialize<X, int(const std::string&)>::value; // prints 1
In上面的例子, has_serialize
以上是C 11 类型特征如何检测具有特定签名的成员函数的存在?的详细内容。更多信息请关注PHP中文网其他相关文章!