【发布时间】:2010-11-13 00:32:33
【问题描述】:
我正在尝试创建一个函数,该函数可以使用带有 0、1 或 2 个参数的 lambda 调用。由于我需要代码在 g++ 4.5 和 vs2010 上工作(它不支持可变参数模板或 lambda 转换为函数指针),所以我想出的唯一想法是根据 arity 选择要调用的实现。以下是我对这应该如何看待的非工作猜测。有什么方法可以修复我的代码,还是有更好的方法来解决这个问题?
#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 函数的代码示例吗?