Reputation: 912
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?
Upvotes: 0
Views: 456
Reputation: 206729
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);
Upvotes: 6