Reputation: 6084
I have problems to compile the following small code fragment. Visual Studio 2015 has problems in the deduction of the type of remover
. Can someone explain me why and how to fix this error?
My idea was to create a reuseable function deleting the first occurence of a value in a given STL container under some user definable predicate.
#include <algorithm>
#include <iostream>
#include <iterator>
#include <functional>
#include <vector>
template<typename T>
auto removeOnlyOnce = [](std::vector<T>& v, const std::function<bool(const T&)>& pred) {
auto iter = std::find_if(v.begin(), v.end(), pred);
if (iter != v.end()) {
v.erase(iter);
}
};
int main(int argc, char** args) {
std::vector<int> v{ 1,2,3,4,2,2,3 };
// Works
std::function<bool(const int&)> isTwoPred = [](int x) { return x == 2; };
removeOnlyOnce<int>(v, isTwoPred);
// Also works
removeOnlyOnce<int>(v, [](const int x)->bool { return x == 2; });
// Gives compile error: C3538
// auto remover = std::bind(removeOnlyOnce<int>, v, std::placeholders::_1);
// remover([](const int x)->bool { return true; });
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
}
The compiler issues the following warning:
main.cpp(26): error C3538: In einer Deklaratorliste muss "auto" immer in denselben Typ hergeleitet werden.
main.cpp(26): note: kann "<lambda_d00b55a1f2cac59f0efd4a81f45edea3>" sein
main.cpp(26): note: oder "std::_Binder<std::_Unforced,<lambda_d00b55a1f2cac59f0efd4a81f45edea3> &,std::vector<int,std::allocator<_Ty>> &,const std::_Ph<1> &>"
with
[
_Ty=int
]
Compiling with Wandbox and Option C++11 gives the following warning, which might be important:
prog.cc:8:6: warning: variable templates are a C++14 extension [-Wc++14-extensions]
auto removeOnlyOnce = [](std::vector<T>& v, const std::function<bool(const T&)>& pred) {
^
1 warning generated.
Upvotes: 0
Views: 68
Reputation: 3477
This lambda is not local. Please omit the &
in [&]
and you should be fine. Maybe a little cryptic, what I wrote: In other words, you don't have a this
to capture.
Upvotes: 1