I'm trying to use STL, but the following doesn't compile. main.cpp:
#include <set>
#include <algorithm>
using namespace std;
class Odp
{
public:
set<int> nums;
bool IsOdd(int i)
{
return i % 2 != 0;
}
bool fAnyOddNums()
{
set<int>::iterator iter = find_if(nums.begin(), nums.end(), &Odp::IsOdd);
return iter != nums.end();
}
};
int main()
{
Odp o;
o.nums.insert(0);
o.nums.insert(1);
o.nums.insert(2);
}
The error is:
error C2064: term does not evaluate to a function taking 1 arguments
1> c:\program files\microsoft visual studio 10.0\vc\include\algorithm(95) : see reference to function template instantiation '_InIt std::_Find_if<std::_Tree_unchecked_const_iterator<_Mytree>,_Pr>(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _InIt=std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>,
1> _Mytree=std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>,
1> _Pr=bool (__thiscall Odp::* )(int)
1> ]
1> main.cpp(20) : see reference to function template instantiation '_InIt std::find_if<std::_Tree_const_iterator<_Mytree>,bool(__thiscall Odp::* )(int)>(_InIt,_InIt,_Pr)' being compiled
1> with
1> [
1> _InIt=std::_Tree_const_iterator<std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>>,
1> _Mytree=std::_Tree_val<std::_Tset_traits<int,std::less<int>,std::allocator<int>,false>>,
1> _Pr=bool (__thiscall Odp::* )(int)
1> ]
What am I doing wrong?
It needs to be declared static:
static bool IsOdd(int i)
Otherwise, you'd be asking find_if to call an instance method without an instance.
The problem is you are passing a pointer to member function. To call that function you would also need a pointer to this but the find_if doesn't let you to pass it. A solution is to wrap it using a function object, see Boost Bind (http://www.boost.org/doc/libs/1_43_0/libs/bind/bind.html) and Boost Function (http://www.boost.org/doc/libs/1_37_0/doc/html/function.html).
IsOdd does not use the class's internals in any way, so don't make it a member function. Instead, pull it out as a standalone function. Then you can call find_if with &IsOdd.
However, there is a benefit to taking things a step further and defining it as a function object:
#include <functional>
struct IsOdd : public unary_function<int, bool>
{
bool operator()(int i) const { return i % 2 != 0; }
};
Then calling find_if with IsOdd() will inline the code within the find_if loop instead of dereferencing a function pointer and making a function call.
Related
Given the following code :-
#include <algorithm>
#include <iostream>
#include <functional>
#include <string>
void func(std::function<void(void)> param)
{
param();
}
void func(std::function<void(int)> param)
{
param(5);
}
int main(int argc, char* argv[])
{
func([] () { std::cout << "void(void)" << std::endl; });
func([] (int i) { std::cout << "void(int): " << i << std::endl; });
std::string line;
std::getline(std::cin, line);
return 0;
}
Compile error from VS2010 :-
CppTest.cpp(18): error C2668: 'func' : ambiguous call to overloaded function
1> CppTest.cpp(11): could be 'void func(std::tr1::function<_Fty>)'
1> with
1> [
1> _Fty=void (int)
1> ]
1> CppTest.cpp(6): or 'void func(std::tr1::function<_Fty>)'
1> with
1> [
1> _Fty=void (void)
1> ]
1> while trying to match the argument list '(`anonymous-namespace'::<lambda0>)'
1>CppTest.cpp(19): error C2668: 'func' : ambiguous call to overloaded function
1> CppTest.cpp(11): could be 'void func(std::tr1::function<_Fty>)'
1> with
1> [
1> _Fty=void (int)
1> ]
1> CppTest.cpp(6): or 'void func(std::tr1::function<_Fty>)'
1> with
1> [
1> _Fty=void (void)
1> ]
1> while trying to match the argument list '(`anonymous-namespace'::<lambda1>)'
Compile error from g++-4.5
program2.cpp: In function ‘int main(int, char**)’:
program2.cpp:18:68: error: call of overloaded ‘func(main(int, char**)::<lambda()>)’ is ambiguous
program2.cpp:6:10: note: candidates are: void func(std::function<void()>)
program2.cpp:11:10: note: void func(std::function<void(int)>)
program2.cpp:19:79: error: call of overloaded ‘func(main(int, char**)::<lambda(int)>)’ is ambiguous
program2.cpp:6:10: note: candidates are: void func(std::function<void()>)
program2.cpp:11:10: note: void func(std::function<void(int)>)
So it seems the compiler can't figure out that a lambda [] () -> void can only be assigned to a std::function<void(void)>, and a lambda [] (int) -> void can only be assigned to a std::function<void(int)>. Is this supposed to happen or just a deficiency in the compilers?
Is this supposed to happen or just a deficiency in the compilers?
This is supposed to happen. std::function has a constructor template that can take an argument of any type. The compiler can't know until after a constructor template is selected and instantiated that it's going to run into errors, and it has to be able to select an overload of your function before it can do that.
The most straightforward fix is to use a cast or to explicitly construct a std::function object of the correct type:
func(std::function<void()>([](){}));
func(std::function<void(int)>([](int){}));
If you have a compiler that supports the captureless-lambda-to-function-pointer conversion and your lambda doesn't capture anything, you can use raw function pointers:
void func(void (*param)()) { }
void func(void (*param)(int)) { }
(It looks like you are using Visual C++ 2010, which does not support this conversion. The conversion was not added to the specification until just before Visual Studio 2010 shipped, too late to add it in.)
To explain the problem in a bit more detail, consider the following:
template <typename T>
struct function {
template <typename U>
function(U f) { }
};
This is basically what the std::function constructor in question looks like: You can call it with any argument, even if the argument doesn't make sense and would cause an error somewhere else. For example, function<int()> f(42); would invoke this constructor template with U = int.
In your specific example, the compiler finds two candidate functions during overload resolution:
void func(std::function<void(void)>)
void func(std::function<void(int)>)
The argument type, some unutterable lambda type name that we will refer to as F, doesn't match either of these exactly, so the compiler starts looking at what conversions it can do to F to try and make it match one of these candidate functions. When looking for conversions, it finds the aforementioned constructor template.
All the compiler sees at this point is that it can call either function because
it can convert F to std::function<void(void)> using its converting constructor with U = F and
it can convert F to std::function<void(int)> using its converting constructor with U = F.
In your example it is obvious that only one of these will succeed without error, but in the general case that isn't true. The compiler can't do anything further. It has to report the ambiguity and fail. It can't pick one because both conversions are equally good and neither overload is better than the other.
I'm trying to use std::map like in example below:
#include <map>
#include <algorithm>
int wmain(int argc, wchar_t* argv[])
{
typedef std::map<int, std::wstring> TestMap;
TestMap testMap;
testMap.insert(std::make_pair(0, L"null"));
testMap.insert(std::make_pair(1, L"one"));
testMap.erase(std::remove_if(testMap.begin(), testMap.end(), [&](const TestMap::value_type& val){ return !val.second.compare(L"one"); }), testMap.end());
return 0;
}
And my compiler (VS2010) gives me following message:
>c:\program files\microsoft visual studio 10.0\vc\include\utility(260): error C2166: l-value specifies const object
1> c:\program files\microsoft visual studio 10.0\vc\include\utility(259) : while compiling class template member function 'std::pair<_Ty1,_Ty2> &std::pair<_Ty1,_Ty2>::operator =(std::pair<_Ty1,_Ty2> &&)'
1> with
1> [
1> _Ty1=const int,
1> _Ty2=std::wstring
1> ]
1> e:\my examples\с++\language tests\maptest\maptest\maptest.cpp(8) : see reference to class template instantiation 'std::pair<_Ty1,_Ty2>' being compiled
1> with
1> [
1> _Ty1=const int,
1> _Ty2=std::wstring
1> ]
I can't understand why opertor = is called though I pass val in lambda-function by reference.
Could you explain what I am doing wrong?
You cannot use std::remove_if with an associative container, because that algorithm works by overwriting removed elements with the subsequent ones: the problem here is that keys of a map are constant, in order to prevent you (or the std::remove_if algorithm) from messing up with the internal ordering of the container.
To remove elements from a map conditionally, rather do this:
for (auto iter = testMap.begin(); iter != testMap.end();)
{
if (!iter->second.compare(L"one")) // Or whatever your condition is...
{
testMap.erase(iter++);
}
else
{
++iter;
}
}
Here is a live example.
The following is cute little template that I use often. Simply tells me if the given element is a member of a collection (which itself must be compatible with the find_if template):
// returns true if a given collection contains the given element
// NOTE: This is NOT optimized for associative containers!
template <typename ELEMENT, typename COLLECTION, typename PREDICATE>
bool contains(const COLLECTION & collection, ELEMENT element, PREDICATE predicate)
{
return collection.end() != std::find_if(collection.begin(), collection.end(), boost::bind(predicate, element, _1));
}
I'm finding that VC2012 balks if I try to use a lambda as the predicate:
if (!contains(specs, str, [] (CString pathname, CString pattern) { return AsBool(PathMatchSpec(pathname, pattern)); }))
continue;
VS2012SP1 spits out the following for the above context:
1>c:\users\steve\projects\cimex cad-cam\15.0\3rd party\boost\boost\bind\bind.hpp(69): error C2039: 'result_type' : is not a member of 'CMacroInterpreter::GetDirectoryOf::<lambda_60eac39ee69a5bdc77e08d06d79ae4c4>'
1> c:\users\steve\projects\cimex cad-cam\15.0\cimex application\cimcad\macro directory.cpp(166) : see declaration of 'CMacroInterpreter::GetDirectoryOf::<lambda_60eac39ee69a5bdc77e08d06d79ae4c4>'
1> c:\users\steve\projects\cimex cad-cam\15.0\3rd party\boost\boost\bind\bind_template.hpp(15) : see reference to class template instantiation 'boost::_bi::result_traits<R,F>' being compiled
1> with
1> [
1> R=boost::_bi::unspecified,
1> F=CMacroInterpreter::GetDirectoryOf::<lambda_60eac39ee69a5bdc77e08d06d79ae4c4>
1> ]
1> c:\users\steve\projects\cimex cad-cam\15.0\mfc toolbox\miscellaneous.h(360) : see reference to class template instantiation 'boost::_bi::bind_t<R,F,L>' being compiled
1> with
1> [
1> R=boost::_bi::unspecified,
1> F=CMacroInterpreter::GetDirectoryOf::<lambda_60eac39ee69a5bdc77e08d06d79ae4c4>,
1> L=boost::_bi::list2<boost::_bi::value<CString>,boost::arg<1>>
1> ]
1> c:\users\steve\projects\cimex cad-cam\15.0\cimex application\cimcad\macro directory.cpp(166) : see reference to function template instantiation 'bool contains<CString,substring_container_adapter,CMacroInterpreter::GetDirectoryOf::<lambda_60eac39ee69a5bdc77e08d06d79ae4c4>>(const COLLECTION &,ELEMENT,PREDICATE)' being compiled
1> with
1> [
1> COLLECTION=substring_container_adapter,
1> ELEMENT=CString,
1> PREDICATE=CMacroInterpreter::GetDirectoryOf::<lambda_60eac39ee69a5bdc77e08d06d79ae4c4>
1> ]
I'm unclear on how to coerce things to accept the predicate lambda. Seems that boost is unable to deduce the return type of the lambda. And I'm unclear on what I can do to fix that?
I could define a local std::binary_function derivative functor. Just seems like it would be better to fix contains<> to allow it to handle lambdas directly.
It seems to be an issue with boost::bind. Using std::bind instead, your code builds fine with lambdas in VS2012:
#include <functional>
#include <algorithm>
#include <vector>
template <typename ELEMENT, typename COLLECTION, typename PREDICATE>
bool contains(const COLLECTION & collection, ELEMENT element, PREDICATE predicate)
{
return collection.end() != std::find_if(collection.begin(), collection.end(), std::bind(predicate, element, std::placeholders::_1));
}
std::vector<int> a;
int main()
{
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(42);
bool c = contains(a, 42, [](int a, int b) { return a == b; });
return 0;
}
The same code builds just fine with g++ as well.
You could always try using another lambda:
template <typename ELEMENT, typename COLLECTION, typename PREDICATE>
bool contains(const COLLECTION & collection, ELEMENT element, PREDICATE predicate)
{
typedef typename COLLECTION::value_type VALUE;
return collection.end() != std::find_if(collection.begin(), collection.end(),
[&]( VALUE const & e ){ return predicate( element, e ); });
}
The last line here:
typedef boost::variant<std::vector<int>, std::vector<float>> C;
class A: public boost::static_visitor<>
{
public:
void operator()(const std::vector<int>& value) const
{
}
void operator()(const std::vector<float>& value) const
{
}
};
C container(std::vector<float>());
boost::apply_visitor(A(), container );
Is giving me the error:
c:\boost_1_49_0\boost\variant\detail\apply_visitor_unary.hpp(60): error C2228: left of '.apply_visitor' must have class/struct/union
1> type is 'boost::variant<T0_,T1> (__cdecl &)'
1> with
1> [
1> T0_=std::vector<int>,
1> T1=std::vector<float>
1> ]
1> c:\visual studio 2010\projects\db\xxx\main.cpp(255) : see reference to function template instantiation 'void boost::apply_visitor<A,C(std::vector<_Ty> (__cdecl *)(void))>(Visitor &,Visitable (__cdecl &))' being compiled
1> with
1> [
1> _Ty=float,
1> Visitor=A,
1> Visitable=C (std::vector<float> (__cdecl *)(void))
What is the problem here? Is it sensible in you opinion to have a container type C which such a definition?
I am using the following type throughout my code:
typedef boost::variant<int, float, ...> Type;
Do you think it would be wiser to use this container definition instead:
typedef std::vector<Type> C; // mixed container
Why?
Your problem is that this
C container(std::vector<float>());
is a function declaration (that’s the most vexing parse) (a function container which takes a function returning std::vector<float> as its sole argument, and returns C). Easy fix: extra parentheses:
C container((std::vector<float>()));
The fact that you’re using containers in the variant is irrelevant to the problem. The same would have happened with boost::variant<int, float>.
Given the following code :-
#include <algorithm>
#include <iostream>
#include <functional>
#include <string>
void func(std::function<void(void)> param)
{
param();
}
void func(std::function<void(int)> param)
{
param(5);
}
int main(int argc, char* argv[])
{
func([] () { std::cout << "void(void)" << std::endl; });
func([] (int i) { std::cout << "void(int): " << i << std::endl; });
std::string line;
std::getline(std::cin, line);
return 0;
}
Compile error from VS2010 :-
CppTest.cpp(18): error C2668: 'func' : ambiguous call to overloaded function
1> CppTest.cpp(11): could be 'void func(std::tr1::function<_Fty>)'
1> with
1> [
1> _Fty=void (int)
1> ]
1> CppTest.cpp(6): or 'void func(std::tr1::function<_Fty>)'
1> with
1> [
1> _Fty=void (void)
1> ]
1> while trying to match the argument list '(`anonymous-namespace'::<lambda0>)'
1>CppTest.cpp(19): error C2668: 'func' : ambiguous call to overloaded function
1> CppTest.cpp(11): could be 'void func(std::tr1::function<_Fty>)'
1> with
1> [
1> _Fty=void (int)
1> ]
1> CppTest.cpp(6): or 'void func(std::tr1::function<_Fty>)'
1> with
1> [
1> _Fty=void (void)
1> ]
1> while trying to match the argument list '(`anonymous-namespace'::<lambda1>)'
Compile error from g++-4.5
program2.cpp: In function ‘int main(int, char**)’:
program2.cpp:18:68: error: call of overloaded ‘func(main(int, char**)::<lambda()>)’ is ambiguous
program2.cpp:6:10: note: candidates are: void func(std::function<void()>)
program2.cpp:11:10: note: void func(std::function<void(int)>)
program2.cpp:19:79: error: call of overloaded ‘func(main(int, char**)::<lambda(int)>)’ is ambiguous
program2.cpp:6:10: note: candidates are: void func(std::function<void()>)
program2.cpp:11:10: note: void func(std::function<void(int)>)
So it seems the compiler can't figure out that a lambda [] () -> void can only be assigned to a std::function<void(void)>, and a lambda [] (int) -> void can only be assigned to a std::function<void(int)>. Is this supposed to happen or just a deficiency in the compilers?
Is this supposed to happen or just a deficiency in the compilers?
This is supposed to happen. std::function has a constructor template that can take an argument of any type. The compiler can't know until after a constructor template is selected and instantiated that it's going to run into errors, and it has to be able to select an overload of your function before it can do that.
The most straightforward fix is to use a cast or to explicitly construct a std::function object of the correct type:
func(std::function<void()>([](){}));
func(std::function<void(int)>([](int){}));
If you have a compiler that supports the captureless-lambda-to-function-pointer conversion and your lambda doesn't capture anything, you can use raw function pointers:
void func(void (*param)()) { }
void func(void (*param)(int)) { }
(It looks like you are using Visual C++ 2010, which does not support this conversion. The conversion was not added to the specification until just before Visual Studio 2010 shipped, too late to add it in.)
To explain the problem in a bit more detail, consider the following:
template <typename T>
struct function {
template <typename U>
function(U f) { }
};
This is basically what the std::function constructor in question looks like: You can call it with any argument, even if the argument doesn't make sense and would cause an error somewhere else. For example, function<int()> f(42); would invoke this constructor template with U = int.
In your specific example, the compiler finds two candidate functions during overload resolution:
void func(std::function<void(void)>)
void func(std::function<void(int)>)
The argument type, some unutterable lambda type name that we will refer to as F, doesn't match either of these exactly, so the compiler starts looking at what conversions it can do to F to try and make it match one of these candidate functions. When looking for conversions, it finds the aforementioned constructor template.
All the compiler sees at this point is that it can call either function because
it can convert F to std::function<void(void)> using its converting constructor with U = F and
it can convert F to std::function<void(int)> using its converting constructor with U = F.
In your example it is obvious that only one of these will succeed without error, but in the general case that isn't true. The compiler can't do anything further. It has to report the ambiguity and fail. It can't pick one because both conversions are equally good and neither overload is better than the other.