From: Daniel Krügler on
On 22 Mrz., 13:31, Craig Sanders <rabbitlover2...(a)gmail.com> wrote:
> I'm hoping that someone might please be able to help me out.
>
> Does anyone know if it is possible to pass object member functions (as
> opposed to class member functions) as the 4th and 5th arguments to the
> inner_product function?

Just out of interest: Do you have a Delphi background? -I just
wonder about the unusual nomenclature in the context of C++.

In C++ a static member function is a "class member function"
and a non-static member function is an "object member function".

For solutions, see below:

> class
> TestClass
> {
> // Various function declarations omitted for brevity.
>
> int sumFunction(int a, int b)
> {
> return(a + b);
> }
>
> int productFunction(int a, int b)
> {
> return(a * b);
> }
>
> };
>
> int main(void)
> {
> // Assume vectorA and vectorB are created and populated with
> values.
>
> TestClass testClass;
>
> cout << "Result = " <<
> inner_product
> (
> vectorA.begin(),
> vectorA.end(),
> vectorB.begin(),

Missing initial value. I assume, you have a "0, " here
as one further function argument.

> testClass.sumFunction,
> testClass.productFunction
> ) <<
> endl;
>
> return(0);
> }
>
> I can't seem to get main to compile for the case shown above. However,
> if sumFunction and productFunction are turned into class functions,
> i.e. by prepending their definition with the keyword static, then I
> can get main to compile and work. Is anyone able to tell me why this
> is the case and how I can get inner_product to work with object
> functions?

In the C++03 standard library there is little direct support for
your particular example. You could boost.bind for that as
shown in

http://www.boost.org/doc/libs/1_42_0/libs/bind/bind.html

[e.g. use

bind(&TestClass::sumFunction, ref(testClass), _1)

instead of

testClass.sumFunction
]

or write your own binder, e.g.

struct TestClassBinder {
TestClass& r;
int(TestClass::*p)(int, int);
TestClassBinder(TestClass& r, int(TestClass::*p)(int, int)) : r(r),
p(p) { }
int operator()(int x, int y) const {
return (r.*p)(x, y);
}
};

and replace

testClass.sumFunction,
testClass.productFunction

by

TestClassBinder(testClass, &TestClass::sumFunction),
TestClassBinder(testClass, &TestClass::productFunction)

HTH & Greetings from Bremen,

Daniel Kr�gler



--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]