Functor for Choosing Between Two Functions

2019-07-21 18:17发布

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.

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-07-21 19:18

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.

查看更多
登录 后发表回答