【发布时间】:2011-03-13 13:59:50
【问题描述】:
我最近升级了我的g++,所以我可以享受 lambda 函数。
一切都很棒,我非常感谢那些让 C++ 和 gcc 成为可能的人。只有一件事我似乎无法解决 - 如何将 lambda 的参数模板化?下面是 lambda 用法的基本示例来演示该问题。
示例 #1,一切都很美味:
#include <cstdio>
struct bar {
bar () {}
void say () {
printf ("bar::say()\n");
}
void say () const {
printf ("bar::say() const\n");
}
};
template <typename T>
void do_work (const T & pred) {
bar b;
pred (b);
}
int main () {
do_work ([] (bar & b) { b.say (); });
}
现在,假设do_work 现在使用不同的参数类型调用谓词两次。所以这里是例子#2:
#include <cstdio>
struct foo {
foo () {}
void say () {
printf ("foo::say()\n");
}
void say () const {
printf ("foo::say() const\n");
}
};
struct bar {
bar () {}
void say () {
printf ("bar::say()\n");
}
void say () const {
printf ("bar::say() const\n");
}
};
template <typename T>
void do_work (const T & pred) {
const foo f;
bar b;
pred (f);
pred (b);
}
int main () {
do_work ([] (auto & b) { b.say (); });
}
注意auto 关键字。我还尝试就地对其进行模板化。不要试图用 gcc 编译它,这是我得到的:
./test.cpp:31:5: internal compiler error: Segmentation fault
Please submit a full bug report,
with preprocessed source if appropriate.
See <http://gcc.gnu.org/bugs.html> for instructions.
但你明白了。理论上,我可以用新的函数声明风格来解决它,但这不是重点。这是我真正想要做的,但使用了简化的语法(为简单起见,foo、bar 和 do_work 被剥离):
struct pred_t {
pred_t () = default;
template <typename T>
void operator () (T && obj) const {
obj.say ();
}
};
int main () {
do_work (pred_t ());
}
有没有办法,或者至少计划,添加对不完全专用的 lambda 函数的支持,以便它们的行为类似于 template <typename T> operator () (T &&) 的谓词?我什至不知道如何命名它,也许是 lambda 谓词?请让我知道你的想法!谢谢!
【问题讨论】:
标签: c++ templates c++11 lambda