Re: Help with templates and code generalization
StephQ wrote:
class Doubler {
public:
double foo(double x) const { return 2*x; }
Drop the 'const'.
Is there a specific reason to drop the const?
Because with the 'const' it doesn't copmile?... <shrug> Dunno...
I would like to avoid it, as this would imply also dropping the const
qualifyer from nearly all other const member functions of the class
(as they use this function a lot).
You'll need to dig this out yourself, I'm afraid. Or hope that somebody
else would chime in... James Kanze recently did a lot of correcting of
my posts, perhaps he's got some idea (which I am sure he has)?
int main() {
plot(cout, mem_fun1(&Doubler::foo));
Change to
Doubler d;
plot(cout, bind1st(mem_fun1(&Doubler::foo), &d));
Otherwise you're trying to make the program call a non-static member
function without an instance.
Why this example works?
Not sure what you mean. You sound like if some other example works,
so should anything you code. You don't use 'for_each', do you? Why
then compare bread and cheese here? In the example below the 'shapes'
vector contains all the instances on which 'mem_fun' "operates". In
your example, you _needed_ to supply the instance.
Draw is not a static member function.
And it's non-const as well. So? You could even name your function
'draw', and it wouldn't make an iota of difference. The main element
here is the presence of _an_instance_ of your class. Here there is
a whole vector of them. In your code there wasn't _any_.
#include <iostream>
#include <vector>
#include <functional>
using namespace std;
class Shape {
public:
virtual void draw(){cout << "Drawing a shape\n"; };
};
class Triangle : public Shape {
void draw() {cout << "Drawing a triangle\n"; }
};
class Square : public Shape {
void draw() {cout << "Drawing a square\n"; }
};
int main() {
vector<Shape*> shapes;
Triangle t1,t2;
Square s1, s2;
shapes.push_back(&t1);
shapes.push_back(&s1);
shapes.push_back(&t2);
shapes.push_back(&s2);
for_each( shapes.begin(), shapes.end(), mem_fun(&Shape::draw));
}
From:
http://www-h.eng.cam.ac.uk/help/tpl/languages/C++/mem_fun.html
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask