R
red floyd
Both gcc 3.3.1 and MSVC 7.1 complain about the second for_each() call
in the following code. Why can't I use bind2nd for a functor with a non-const
reference as the second parameter? I have to use kludge it by using something like
KludgeFunctor().
---------------------------
#include <vector>
#include <algorithm>
#include <functional>
class A {
public:
A() { }
A(const A&) { }
};
class B {
public:
B() { }
B(const B&) { }
};
class GoodFunctor : public std::binary_function<A, B, void>
{
public:
void operator()(const A&, const B&) const { }
};
class BadFunctor : public std::binary_function<A, B, void>
{
public:
void operator()(const A&, B&) const { }
};
class KludgeFunctor : public std::unary_function<A, void>
{
B& b;
public:
KludgeFunctor(B& b_) : b(b_) { }
void operator()(const A&) const { }
};
void f()
{
std::vector<A> v;
B b;
// this compiles
std::for_each(v.begin(),
v.end(),
std::bind2nd(GoodFunctor(), b));
// this generates an error
std::for_each(v.begin(),
v.end(),
std::bind2nd(BadFunctor(), b));
// this is the workaround for BadFunctor
std::for_each(v.begin(),
v.end(),
KludgeFunctor(b));
}
----------------------------------
in the following code. Why can't I use bind2nd for a functor with a non-const
reference as the second parameter? I have to use kludge it by using something like
KludgeFunctor().
---------------------------
#include <vector>
#include <algorithm>
#include <functional>
class A {
public:
A() { }
A(const A&) { }
};
class B {
public:
B() { }
B(const B&) { }
};
class GoodFunctor : public std::binary_function<A, B, void>
{
public:
void operator()(const A&, const B&) const { }
};
class BadFunctor : public std::binary_function<A, B, void>
{
public:
void operator()(const A&, B&) const { }
};
class KludgeFunctor : public std::unary_function<A, void>
{
B& b;
public:
KludgeFunctor(B& b_) : b(b_) { }
void operator()(const A&) const { }
};
void f()
{
std::vector<A> v;
B b;
// this compiles
std::for_each(v.begin(),
v.end(),
std::bind2nd(GoodFunctor(), b));
// this generates an error
std::for_each(v.begin(),
v.end(),
std::bind2nd(BadFunctor(), b));
// this is the workaround for BadFunctor
std::for_each(v.begin(),
v.end(),
KludgeFunctor(b));
}
----------------------------------