问题描述
让我们说我有这些代码行;
Lets say I have these lines of code;
std::vector<int> ints;
std::for_each(ints.begin(), ints.end(), [](int& val){ val = 7; });
但是,我不想在lambda函数中指定参数类型,即,我想写
However, I dont want to specify the argument type in my lambda functions, ie, I want to write something like this;
std::for_each(ints.begin(), ints.end(), [](auto& val){ val = 7; });
反正还有什么可以实现的吗?
Is there anyway this can be achieved?
(boost :: lambda不需要指定类型...)
更新:
Update:
现在我使用一个宏: #define _A(容器)decltype(* std :: begin(container))
所以我可以做:
For now I use a macro: #define _A(container) decltype(*std::begin(container))
so I can do:
std::for_each(ints.begin(), ints.end(), [](_A(ints)& val){ val = 7; });
推荐答案
否。在C ++委员会的讨论中,多态lambda是指此功能,但尚未标准化。必须指定lambda的参数类型。
No. "Polymorphic lambdas" is what this feature was referred to during the C++ committee discussions, and it was not standardized. The parameter types of a lambda must be specified.
尽管可以使用 decltype
:
std::for_each(ints.begin(), ints.end(), [](decltype(*ints.begin())& val){ val = 7; });
这篇关于参数类型自动推导和匿名Lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!