0

In C++, let's say that I have the following header file:

class Foo {
  static int func0 (int, int);
  static int func1 (int, int);
  static int func2 (int, int);
  static int func3 (int, int);
};

Is there anyway to do this via typedefs?

I tried:

class Foo {
  typedef int(*func)(int, int);
  static func func1;
  static func func2;
  static func func3;
  static func func4;
};

And then in a cpp file

int Foo::func1(int a, int b) { return a + b; }

but I get the error:

Redefinition of func1 as different kind of symbol

hmjd
  • 120,187
  • 20
  • 207
  • 252
  • What's the problem you're trying to solve? I strongly suspect that there is an easy way of achieving what you want, but it depends on what your overall goal is. – Component 10 Jun 28 '12 at 09:08
  • Your problem is probably in the design of your code. Post the real example with comments what the functions should do. – Thomas Jun 28 '12 at 09:11

2 Answers2

1

func1 has been declared as a function pointer, not as a function which you are trying to define it as.

Example use of a function pointer:

typedef int (*func_t)(int, int);

int func1(int a, int b) { return a + b; }
int func2(int a, int b) { return a * b; }

funct_t op = func1;
assert(9 == op(4, 5));

op = func2;
assert(20 == op(4, 5));

Having said that, I am unsure what your exact intention is.

hmjd
  • 120,187
  • 20
  • 207
  • 252
1

You can't do what you want with typedefs, but if you really, really want to do this, you could use the preprocessor.

#define MAKE_MY_FUNC(funcname) static int funcname(int, int)

class Foo {
  MAKE_MY_FUNC(func0);
  MAKE_MY_FUNC(func1);
  MAKE_MY_FUNC(func2);
  MAKE_MY_FUNC(func3);
};

#undef MAKE_MY_FUNC  // To make sure that you don't get preprocessor misery afterwards.
Joris Timmermans
  • 10,814
  • 2
  • 49
  • 75