我最近升级了我,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 (); });
}
Run Code Online (Sandbox Code Playgroud)
现在,假设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 (); });
}
Run Code Online (Sandbox Code Playgroud)
注意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.
Run Code Online (Sandbox Code Playgroud)
但是你明白了.理论上,我可以用新的函数声明样式来解决它,但这不是重点.以下是我真的想做,但简化的语法(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 ());
}
Run Code Online (Sandbox Code Playgroud)
有没有办法,或者至少是计划,为不完全专业化的lambda函数添加支持,以便它们有点像谓词一样template <typename T> operator () (T &&)?我甚至不知道怎么命名,lambda谓词也许?请让我知道你的想法!谢谢!