2

Googling for C++ functor syntax brings a lot of different results and I don't think I see what need in any of them. Some use templates, some use a single class, others multiple, and still others use structs instead. I'm never sure what specific elements I need for what I want to do. So now, what I want to do:

I have two functions. They both take the exact same parameters, but are named differently and will return a different result, though the return type is also the same, e.g.,

unsigned foo1(char *start, char *end);
unsigned foo2(char *start, char *end);

I just want to choose which function to call depending on the value of a Boolean variable. I could just write a predicate to choose between the two, but that doesn't seem an elegant solution. If this were C, I'd use a simple function pointer, but I've been advised they don't work well in C++.

Edit: Due to restrictions beyond my control, in this scenario, I cannot use C++11.

Eric
  • 2,300
  • 3
  • 22
  • 29

1 Answers1

4

Just use std::function:

std::function<unsigned int(char*, char*)> func = condition ? foo1 : foo2;
//            ^^^^^^^^^^^^^^^^^^^^^^^^^^ function signature

// ...

unsigned int result = func(start, end);

Also, function pointers work fine in C++:

auto func = condition ? foo1 : foo2;

unsigned int result = func(start, end);

But std::function is more flexible.

Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • I do appreciate your answer. I should have mentioned to begin with that I cannot use C++11 for this particular problem. Your answer will be very useful for those who do not have my constraint, so I thank you. – Eric Oct 21 '12 at 16:34
  • @Eric I only used `auto` as an abreviation. If you don't have `auto`, you can do `unsigned int(*func)(char*, char*) = condition ? foo1 : foo2;`. – Seth Carnegie Oct 21 '12 at 16:36