是否有可能写出一个类型特征,比如说is_callable<T>一个对象是否已operator()定义?如果调用运算符的参数事先已知,则很容易,但在一般情况下则不行.当且仅当至少有一个重载调用运算符被定义时,我希望特征返回true.
这个问题是相关的,并且有一个很好的答案,但它不适用于所有类型(仅限于 - 可int转换类型).此外,std::is_function工作,但只适用于正确的C++函数,而不是函子.我正在寻找更通用的解决方案.
可以通过访问它来推断出非泛型lambda的arity operator().
template <typename F>
struct fInfo : fInfo<decltype(&F::operator())> { };
template <typename F, typename Ret, typename... Args>
struct fInfo<Ret(F::*)(Args...)const> { static const int arity = sizeof...(Args); };
Run Code Online (Sandbox Code Playgroud)
对于像没有模板化的东西一样[](int x){ return x; },这很好看operator().
但是,通用lambdas operator()会对模板进行模板化,并且只能访问模板的具体实例 - 这有点问题,因为我无法手动提供模板参数,operator()因为我不知道它是什么.
所以,当然,像
auto lambda = [](auto x){ return x; };
auto arity = fInfo<decltype(lambda)>::arity;
Run Code Online (Sandbox Code Playgroud)
不起作用.
我不知道要投射什么,也不知道提供什么模板参数(或多少)(operator()<??>).
任何想法如何做到这一点?