Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
313 views
in Technique[技术] by (71.8m points)

c++ - Argument type auto deduction and anonymous lambda functions

Lets say I have these lines of code;

std::vector<int> ints;
std::for_each(ints.begin(), ints.end(), [](int& val){ val = 7; });

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 doesn't need types to be specified...)


Update:

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; });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

You can use decltype though:

std::for_each(ints.begin(), ints.end(), [](decltype(*ints.begin())& val){ val = 7; });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...