选择两个函数之间的函子 [英] Functor for Choosing Between Two Functions
问题描述
Googling for C ++函子语法带来了很多不同的结果,我不认为我看到任何需要。一些使用模板,一些使用单个类,其他多个,还有一些使用structs。我不知道我需要什么具体的元素我想做什么。所以现在,我想做什么:
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);
c>
unsigned foo1(char *start, char *end);
unsigned foo2(char *start, char *end);
我只想根据布尔变量的值来选择调用哪个函数。我可以写一个谓词来选择两者之间,但这似乎不是一个优雅的解决方案。如果这是C,我会使用一个简单的函数指针,但我已经被告知他们在C ++中不能很好地工作。
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++.
编辑:
推荐答案
只需使用 std: :function
:
std::function<unsigned int(char*, char*)> func = condition ? foo1 : foo2;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^ function signature
// ...
unsigned int result = func(start, end);
此外,函数指针在C ++中运行正常:
Also, function pointers work fine in C++:
auto func = condition ? foo1 : foo2;
unsigned int result = func(start, end);
但 std :: function
。
这篇关于选择两个函数之间的函子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!