views:

167

answers:

2

I'm trying to create a lookup table of member functions in my code, but it seems to be trying to call my copy constructor, which I've blocked by extending an "uncopyable" class. What I have is something like the following.

enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };

class Foo {
  fun1(Bar b){ ... }
  fun2(Bar b){ ... }
  ...
  void (Foo::*lookup_table[NUM_FUNS])(Bar b);
  Foo(){ 
    lookup_table[FUN1_IDX] = &Foo::fun1;
    lookup_table[FUN2_IDX] = &Foo::fun2;
  }

  void doLookup(int fun_num, Bar b) {
    (this->*lookup_table[fun_num])(b);
  }
};

The error is that the '(this->...' line tries to call the copy constructor, which is not visible. Why is it trying to do this, and what do I have to change so it won't?

A: 

Maybe you should learn what a copy constructor is, before adventuring into member function pointers.

zenerino
+5  A: 

Make them reference parameters.

enum {FUN1_IDX, FUN2_IDX, ..., NUM_FUNS };

class Foo {
  fun1(Bar &b){ ... }
  fun2(Bar &b){ ... }
  ...
  void (Foo::*lookup_table[NUM_FUNS])(Bar &b);
  Foo(){ 
    lookup_table[FUN1_IDX] = &Foo::fun1;
    lookup_table[FUN2_IDX] = &Foo::fun2;
  }

  void doLookup(int fun_num, Bar &b) {
    (this->*lookup_table[fun_num])(b);
  }
};

In C++, otherwise such plain parameters don't just reference objects, but they are those objects themselves. Making them reference parameters will merely reference what is passed. In this matter, C++ has the same semantics as C (in which you would use pointers for that).

Johannes Schaub - litb
Thank you. I was confused by the error message because both Foo and Bar were uncopyable, and I thought it was trying to copy Foo. Of course it was trying to copy Bar.
drhorrible