如何访问 c++0x 中 lambda 的类型?
如何在 C++ 中访问 lambda 函数的参数类型?以下不起作用:
template <class T> struct capture_lambda {
};
template <class R, class T> struct capture_lambda<R(T)> {
static void exec() {
}
};
template <class T> void test(T t) {
capture_lambda<T>::exec();
}
int main() {
test([](int i)->int{ return 0; });
}
上面的代码无法编译,因为编译器选择模板原型而不是专门化。
有办法做到上述吗?
我实际上想要实现的是:我有一个函数列表,我想选择要调用的适当函数。示例:
template <class T, class ...F> void exec(T t, F... f...) {
//select the appropriate function from 'F' to invoke, based on match with T.
}
例如,我想调用采用“int”的函数:
exec(1, [](char c){ printf("Error"); }, [](int i){ printf("Ok"); });
How is it possible to access the types of the parameters of a lambda function in c++? The following does not work:
template <class T> struct capture_lambda {
};
template <class R, class T> struct capture_lambda<R(T)> {
static void exec() {
}
};
template <class T> void test(T t) {
capture_lambda<T>::exec();
}
int main() {
test([](int i)->int{ return 0; });
}
The above does not compile, because the compiler chooses the template prototype instead of the specialization.
Is there a way to do the above?
What I am actually trying to achieve is this: I have a list of functions and I want to select the appropriate function to invoke. Example:
template <class T, class ...F> void exec(T t, F... f...) {
//select the appropriate function from 'F' to invoke, based on match with T.
}
For example, I want to invoke the function that takes 'int':
exec(1, [](char c){ printf("Error"); }, [](int i){ printf("Ok"); });
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是不可能的,lambda 函数是用于创建函数对象而不是实际函数的语法糖。这意味着模板接受一个类,而类没有参数类型的概念。
另请记住,通用函数对象可以具有任意数量的重载
operator()
。This isn't possible, lambda functions are syntactic sugar for creating function objects not actual functions. This means that the template is accepting a class, and classes don't have the concept of argument type.
Also keep in mind that a general function object can have any number of overloaded
operator()
s.