我编写了一个特征类,它可以让我提取有关 C++0x 中函数或函数对象的参数和类型的信息(使用 gcc 4.5.0 进行测试)。一般情况处理函数对象:
template <typename F>
struct function_traits {
template <typename R, typename... A>
struct _internal { };
template <typename R, typename... A>
struct _internal<R (F::*)(A...)> {
// ...
};
typedef typename _internal<decltype(&F::operator())>::<<nested types go here>>;
};
然后我在全局范围内专门研究普通函数:
template <typename R, typename... A>
struct function_traits<R (*)(A...)> {
// ...
};
这工作正常,我可以将函数传递到模板或函数对象中,并且它可以正常工作:
template <typename F>
void foo(F f) {
typename function_traits<F>::whatever ...;
}
int f(int x) { ... }
foo(f);
如果不将函数或函数对象传递给foo
,我想传递一个lambda表达式?
foo([](int x) { ... });
这里的问题是,既没有专业化function_traits<>
适用。 C++0x 草案规定表达式的类型是“唯一的、未命名的、非联合类类型”。破坏调用结果typeid(...).name()
表达式上的内容似乎是 gcc 的 lambda 内部命名约定,main::{lambda(int)#1}
,而不是在语法上表示 C++ 类型名的东西。
简而言之,我可以在此处将任何内容放入模板中:
template <typename R, typename... A>
struct function_traits<????> { ... }
这将允许这个特征类接受 lambda 表达式?