Question

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?

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top