C
Capstar
Hi NG,
I have a question on std::for_each. I try to use this in combination
with std::bind2nd to call a method of all functions in a container
(std::set or std::map) and pass that method the second argument of
std::bind2nd.
But for some reason the compiler wants met ot have all const objects,
which obviously doesn't work when the method is non-const.
example:
/** test.cpp **/
#include <set>
#include <algorithm>
class myInt
{
int i_;
public:
myInt(int i): i_(i) {}
int val() const { return i_; }
void setVal(int i) { i_ = i; }
bool operator<(const myInt & rhs) const { return i_ < rhs.i_; }
};
struct intAdder : public std::binary_function<myInt,int,void>
{
void operator()(myInt & ref, int x) const
{
ref.setVal(ref.val() + x);
}
};
int main()
{
std::set<myInt> s;
s.insert( myInt( 3 ) );
s.insert( myInt( 5 ) );
std::for_each(s.begin(), s.end(), std::bind2nd(intAdder(), 2));
return 0;
}
The interesting thing is that this code does compile with
cl /Zi /GX /GR test.cpp (win32 13.10.3077)
but doesn't compile with
g++ -W -Wall test.cpp (gcc 3.2.3)
Mark
I have a question on std::for_each. I try to use this in combination
with std::bind2nd to call a method of all functions in a container
(std::set or std::map) and pass that method the second argument of
std::bind2nd.
But for some reason the compiler wants met ot have all const objects,
which obviously doesn't work when the method is non-const.
example:
/** test.cpp **/
#include <set>
#include <algorithm>
class myInt
{
int i_;
public:
myInt(int i): i_(i) {}
int val() const { return i_; }
void setVal(int i) { i_ = i; }
bool operator<(const myInt & rhs) const { return i_ < rhs.i_; }
};
struct intAdder : public std::binary_function<myInt,int,void>
{
void operator()(myInt & ref, int x) const
{
ref.setVal(ref.val() + x);
}
};
int main()
{
std::set<myInt> s;
s.insert( myInt( 3 ) );
s.insert( myInt( 5 ) );
std::for_each(s.begin(), s.end(), std::bind2nd(intAdder(), 2));
return 0;
}
The interesting thing is that this code does compile with
cl /Zi /GX /GR test.cpp (win32 13.10.3077)
but doesn't compile with
g++ -W -Wall test.cpp (gcc 3.2.3)
Mark