From: Craig Sanders on 21 Mar 2010 21:31 Hello all. 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? 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(), 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? Thanks in advance. - Craig -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
From: Daniel T. on 22 Mar 2010 22:41 Craig Sanders <rabbitlover2007(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? (You mean the 5th and 6th arguments...) Yes. I explained how to do this in the comp.lang.c++ newsgroup. The short answer is to use a binder: class Binder { typedef int (TestClass::*Func)(int, int); Func func; TestClass* testClass; public: Binder(Func func, TestClass& testClass): func(func), testClass(&testClass) { } int operator()(int a, int b) { return (testClass->*func)(a, b); } }; void foo(TestClass& testClass, vector<int>& a, vector<int>& b) { int result = inner_product(a.begin(), a.end(), b.begin(), 0, Binder(&TestClass::sumFunction, testClass), Binder(&TestClass::productFunction, testClass)); } But as I explained in the other newsgroup, I seriously doubt you want to do this. Even if you do want to do this, sumFunction and productFunction should probably be const. In the example code you provided, there is no need to use member function (whether static or not) at all. Simply: inner_product(a.begin(), a.end(), b.begin(), 0); will do the trick. Finally, note that the Binder class above can be made more generic with judicious use of templates if you really need it. -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] [ comp.lang.c++.moderated. First time posters: Do this! ]
|
Pages: 1 Prev: CRTP Next: Is it possible to use object functions as arguments to the inner_product algorithm? |