模板参数推导,我有以下模板声明C++与lambda表达式
template<typename T>
void foo(function<void(T)> f){
// ...
};
但是,当我这样称呼它
foo([](string s){ });
// visual studio 13 error message =>
// Error: void foo(std::function<void(_Type)>)' :
//could not deduce template argument for 'std::function<void(_Type)>'
//from 'main::<lambda_58b8897709e10f89bb5d042645824f66>
模板参数推导失败。 为什么?如何解决它?
我有可变参数模板
template<typename ... Tn>
void foo(function<void(Tn ...)> f){
// ...
};
int main() {
foo<string,bool>([](string s,bool b){ }); // Works
foo([](string s,bool b){ }); // Fails
}
同样的问题,但是,如果我明确地转换它的工作拉姆达(!)
foo((function<void(string,bool)>) [](string s,bool b){ }); // Works
// Or even a simpler syntax with a macro
#define lmda_(a) (function<void a>)[&] a
foo(lmda_((string s, bool b)) { }); // Works (note the extra())
为什么模板参数推导失败?以及如何解决它?
http://stackoverflow.com/q/11500881/560648 –
这应该工作,并且可能是更好... 的#define lmda_(......)(函数<空隙(__VA_ARGS __)>)[&](__VA_ARGS__) - > foo(lmda_(string s,bool b){}); e:你需要使用两个下划线前后缀va_args(它们在这里变成粗体格式文本) – Shaggi
*机器人的Lambda平庸定律*:如果你的设计关心lambda表达式,那就错了。 (也简称为“lambda不是特别的”) –