0

I need a switch for different functions to circumvent frequent if-directions. It should work similar to the following code, encapsulated in a class:

#include<iostream>
#include<stdlib.h>

using namespace std;

template<class T>
class MaxSwitch
{
public:
typedef T (MaxSwitch::*Max_P)(T,T);
Max_P fooC_P;

MaxSwitch(int Q) {
    if (Q==0)fooC_P=&MaxSwitch::MaxVal1;
    else fooC_P=&MaxSwitch::MaxVal2;
}

inline T MaxVal1(T kx,T MAX)
{
    return kx+1;
}

inline T MaxVal2(T kx,T MAX)
{
    return MAX;
}

};

 int main( int argc, char ** argv )
{
int Q=atoi ( argv[1] );
MaxSwitch<int> MAXSW(Q);


int MAX=5;

for ( int kx=0;kx<MAX;kx++ ) for ( int ky=0;ky<(MAXSW.fooC_P)(kx,MAX);ky++ )
    {
        cout<<"(kx="<<kx<<", ky="<<ky<<endl;
    }

return 0;
 }

I have now the trivial problem that the function call (MAXSW.fooC_P)(ky,MAX) is wrong. How to do it properly?

2
  • a quick note: your naming convention for parameters makes the code not that readable.. Commented May 19, 2012 at 8:35
  • (Jay D is being nice with "not that readable" - I'd have said completely confusing.) Commented May 19, 2012 at 8:36

1 Answer 1

6

MAXSW.fooC_P is the pointer-to-member-function that you need to call, and MAXSW is the object you want to call it on. So you can call that function with:

(MAXSW.*(MAXSW.fooC_P))(ky,MAX);
Sign up to request clarification or add additional context in comments.

1 Comment

Note that (MAXSW.*MAXSW.fooC_P)(ky,MAX) will also work (that is - the inner brackets are redundant).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.