is class visible, is this the correct ?

G

Greg

I want to pass a function (testfn) into a another function (fnmeas).
testfn makes use of an object cx, so is it ok to have cx local to the
file containing testfn ? The fnmeas does not care what cx is as such,
but somehow the scope does not seem right.

example

typedef double fn(const double &x);

in fns.cpp..

myclass cx;

double testfn(const double &y)
{
return y*cx.a*cx.b;
}

void go()
{
cx.a = 1;
cx.b = 2;
fn *p = &testfn;
double x = fnmeas(p);
}

in cv.cpp..

double fnmeas(fn *f)
{
return f(1.5) + f(2.5);
}

Is it better to pass a handle of cx to fnmeas ? How would I do that ?

I may be thinking in non OO terms here, but the idea is to have fnmeas
generic.
 
R

Rolf Magnus

Greg said:
I want to pass a function (testfn) into a another function (fnmeas).
testfn makes use of an object cx, so is it ok to have cx local to the
file containing testfn ? The fnmeas does not care what cx is as such,
but somehow the scope does not seem right.

example

typedef double fn(const double &x);

in fns.cpp..

myclass cx;

double testfn(const double &y)
{
return y*cx.a*cx.b;
}

void go()
{
cx.a = 1;
cx.b = 2;
fn *p = &testfn;
double x = fnmeas(p);
}

in cv.cpp..

double fnmeas(fn *f)
{
return f(1.5) + f(2.5);
}

Is it better to pass a handle of cx to fnmeas ? How would I do that ?

I may be thinking in non OO terms here, but the idea is to have fnmeas
generic.

One way would be to use function objects and templates, similar to what the
standard library does. Maybe something like this (untested):

struct testfn
{
testfn(myclass& obj)
: obj_(obj)
{
}

double operator()(const double& y) const
{
return y*obj_.a*obj_.b;
}

myclass& obj_:
};


void go()
{
myclass cx;
cx.a = 1;
cx.b = 2;
testfn p(cx);
double x = fnmeas(p);
}

template<typename T>
double fnmeas(T f)
{
return f(1.5) + f(2.5);
}
 
G

Greg

Rolf said:
One way would be to use function objects and templates, similar to what the
standard library does. Maybe something like this (untested):

struct testfn
{
testfn(myclass& obj)
: obj_(obj)
{
}

double operator()(const double& y) const
{
return y*obj_.a*obj_.b;
}

myclass& obj_:
};


void go()
{
myclass cx;
cx.a = 1;
cx.b = 2;
testfn p(cx);
double x = fnmeas(p);
}

template<typename T>
double fnmeas(T f)
{
return f(1.5) + f(2.5);
}

Thanks, templates can be neat. I put everything in the class and then
made "testfn" virtual, but I might use a template later.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top