By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,819 Members | 1,185 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,819 IT Pros & Developers. It's quick & easy.

is class visible, is this the correct ?

P: n/a
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.

Oct 3 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Greg wrote:
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);
}

Oct 3 '06 #2

P: n/a

Rolf Magnus wrote:
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.

Oct 3 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.