Functor for Choosing Between Two Functions

℡╲_俬逩灬. 提交于 2019-12-24 02:11:04

问题


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:


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.



来源:https://stackoverflow.com/questions/12993973/functor-for-choosing-between-two-functions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!