有一种(看似)不错的 C++03 方法可以确定一个类型是否具有成员函数或运算符:
https://github.com/jaredhoberock/is_call_possible/blob/master/is_call_possible.hpp
没有现代 C++11 方法可以做到这一点吗?最好不要包含任何外部代码而只使用标准。
最佳答案
这适用于 GitHub 中给出的所有测试用例(演示:http://ideone.com/ZLGp4R):
#include <type_traits>
template <typename C, typename F, typename = void>
struct is_call_possible : public std::false_type {};
template <typename C, typename R, typename... A>
struct is_call_possible<C, R(A...),
typename std::enable_if<
std::is_same<R, void>::value ||
std::is_convertible<decltype(
std::declval<C>().operator()(std::declval<A>()...)
// ^^^^^^^^^^ replace this with the member you need.
), R>::value
>::type
> : public std::true_type {};
关于C++ 11查找类型是否具有成员函数或支持运算符的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17201329/