本文介绍了c ++ 0x:在lambda arity上重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我试图创建一个函数,可以调用一个lambda,需要0,1或2参数。由于我需要代码工作在g ++ 4.5和vs2010(不支持可变参数模板或lambda转换为函数指针),我想出的唯一的想法是选择哪个实现基于arity调用。下面是我的非工作猜测如何应该看起来。有没有办法修复我的代码或有一个更好的方法来做这个一般来说?I'm trying to create a function which can be called with a lambda that takes either 0, 1 or 2 arguments. Since I need the code to work on both g++ 4.5 and vs2010(which doesn't support variadic templates or lambda conversions to function pointers) the only idea I've come up with is to choose which implementation to call based on arity. The below is my non working guess at how this should look. Is there any way to fix my code or is there a better way to do this in general?#include <iostream>#include <functional>using namespace std;template <class Func> struct arity;template <class Func>struct arity<Func()>{ static const int val = 0; };template <class Func, class Arg1>struct arity<Func(Arg1)>{ static const int val = 1; };template <class Func, class Arg1, class Arg2>struct arity<Func(Arg1,Arg2)>{ static const int val = 2; };template<class F>void bar(F f){ cout << arity<F>::val << endl;}int main(){ bar([]{cout << "test" << endl;});} 推荐答案 lambda函数是一个类类型具有单个函数调用操作符。因此,您可以通过获取函数调用操作符的地址并使用重载分辨率来选择要调用的函数来检测函数调用操作符的数量:A lambda function is a class type with a single function call operator. You can thus detect the arity of that function call operator by taking its address and using overload resolution to select which function to call:#include <iostream>template<typename F,typename R>void do_stuff(F& f,R (F::*mf)() const){ (f.*mf)();}template<typename F,typename R,typename A1>void do_stuff(F& f,R (F::*mf)(A1) const){ (f.*mf)(99);}template<typename F,typename R,typename A1,typename A2>void do_stuff(F& f,R (F::*mf)(A1,A2) const){ (f.*mf)(42,123);}template<typename F>void do_stuff(F f){ do_stuff(f,&F::operator());}int main(){ do_stuff([]{std::cout<<"no args"<<std::endl;}); do_stuff([](int a1){std::cout<<"1 args="<<a1<<std::endl;}); do_stuff([](int a1,int a2){std::cout<<"2 args="<<a1<<","<<a2<<std::endl;});}注意:这不能用于函数类型或类类型具有多个函数调用操作符,或非 const 函数调用操作符。Be careful though: this won't work with function types, or class types that have more than one function call operator, or non-const function call operators. 这篇关于c ++ 0x:在lambda arity上重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-09 21:54