0

I have 2 functions with the same input and output types.

uint32_t doWork(uint32_t time);
uint32_t MyClass::DoWork(uint32_t time);

now I want to dependency inject this function into another class to either use one of the functions.

So I thought I could use a function point but this is not working since a function pointer requires the class type to also be used.

Is there any way to store both functions in the same function pointer type and pass it to a constructor?

The function from the class is not static.

Any help is appreciated!

  • If you use the class member, how is it supposed to know which object to act on? – Barmar Nov 18 '16 at 19:53
  • related/dupe: http://stackoverflow.com/questions/30605393/assign-a-member-function-to-a-function-pointer – NathanOliver Nov 18 '16 at 19:53
  • Will an extra level of indirection hurt? – WhiZTiM Nov 18 '16 at 19:59
  • 1
    A pointer to a standalone function is very different than a pointer to a class member method. So no, you cannot store them in the same pointer type, let alone call them the same way. Consider using [`std::function`](http://en.cppreference.com/w/cpp/utility/functional/function) instead of a raw pointer. – Remy Lebeau Nov 18 '16 at 20:06
  • @RemyLebeau Ah I see I come form a c background and programmed c++ 10+ years ago. This is a new development. If you add this as an answer I can accept it. –  Nov 18 '16 at 20:22

1 Answers1

1

I experimented a little bit with my C++ compiler. Here is what I got that seems to be doing the job:

#include <stdio.h>

typedef unsigned int uint32_t;

typedef uint32_t (doWorkPtr) (uint32_t time);

uint32_t doWork(uint32_t time) {
  return time*2;
}

class MyClass {
  public:
  int times;
  int DoWork(uint32_t time) { return time*times; }
};

struct Adapter {
  MyClass* a;
  doWorkPtr* ptr;
  int operator() (uint32_t time) {
    if(a)
      return a->DoWork(time);
    else
      return ptr(time);
  }
};

int main(int argc, char** argv) {
  Adapter* pointers[2];

  MyClass klass;
  klass.times = 3;
  Adapter adapter;
  adapter.a = &klass;
  adapter.ptr = 0;

  Adapter adapter2;
  adapter2.a = 0;
  adapter2.ptr = &doWork;

  pointers[0] = &adapter;
  pointers[1] = &adapter2;

  printf("result1 %i\n", (*pointers[0])(1));
  printf("result2 %i\n", (*pointers[1])(1));

  return 0;
}

Your class would store 'Adapter' pointers instead of plain functions pointers when using this.

Hope it helps!

Giro_AT
  • 46
  • 3