Hi,
how to declare a double dimensional array of pointers to its
member functions in the class?
And how can we access it?
I have done like this
class A;
typedef void (A::*fp)();
class A{
fp array[2][2];
}
and am trying ti call the function like below:
A *aptr = new A;
(aptr->*array[1][1])();
Is this correct?
Regards
Another take on the same thing. Happy to have criticism, but
I don't know what you would be using this for. I would use
vectors instead of arrays. I would not allow public access
to the table (at the very least).
In addition to "the very least", you could perhaps return
a proxy encapsulating the row of a table, and overload the
subscript operator for A and for the proxy, as well as the
function operator for the proxy. This would encapsulate
it nicely and disallow the use of invalid member function
pointers.
#include <vector>
#include <iostream>
// I've moved the typedef to the class. I'm assuming you have
// good reason not to, but I would not make the typedef global.
struct A
{
A()
: callbackTable_( 2, MemFuncSeq( 2 ) )
{
callbackTable_[0][0] = &A::f1;
callbackTable_[0][1] = &A::f2;
callbackTable_[1][0] = &A::f3;
callbackTable_[1][1] = &A::f4;
}
void operator()( int row, int col )
{
(this->*callbackTable_.at( row ).at( col ))();
}
int rowCount() const{ return callbackTable_.size(); }
int colCount() const{ return callbackTable_[0].size(); }
private:
typedef void (A::*PtrMemFunc)();
typedef std::vector<PtrMemFunc> MemFuncSeq;
std::vector<MemFuncSeq> callbackTable_;
void f1(){ std::cout << "f1\n"; }
void f2(){ std::cout << "f2\n"; }
void f3(){ std::cout << "f3\n"; }
void f4(){ std::cout << "f4\n"; }
};
int main()
{
A a;
for( int row = 0; row < a.rowCount(); ++row )
{
for( int col = 0; col < a.colCount(); ++col )
{
a( row, col );
}
}
}
Kind regards,
Werner