函数返回C++11中的函数指针
Function returning function pointer in C++11
我有以下C代码:
inline void ChooseNext ( std::vector<RLS> & rls_vec_left_to_choose_,
int & num_files_left_to_choose_, const int algo_,
std::vector<RLS> & rls_vec_chosen_ )
{
if ( ( num_files_left_to_choose_ > 0 )
&& ( rls_vec_left_to_choose_.size ( ) > 0 ) )
{
switch ( algo_ )
{
case kAlgo1 :
std::sort ( rls_vec_left_to_choose_.begin ( ), rls_vec_left_to_choose_.end ( ), SortFunc1 );
break;
case kAlgo2 :
default:
std::sort ( rls_vec_left_to_choose_.begin ( ), rls_vec_left_to_choose_.end ( ), SortFunc2 );
break;
}
// etc
}
}
其中分拣功能均为以下类型:
bool SortFunc1 ( const RLS & d1, const RLS & d2 ) ;
如何将其更改为接受const int algo_
并返回bool (*) ( const RLS & d1, const RLS & d2 )
的函数,然后删除此函数中的开关情况?我正在尝试以尽可能可读的方式来做这件事,并希望使用C++11特性。
如果是C++,为什么要返回函数指针?您可以使用std::function
代替:
std::function<bool(const RLS &, const RLS &)> ChooseNext(int algo)
{
static const std::vector<std::function<bool(const RLS &, const RLS &)>> st {
SortFunc1,
SortFunc2,
// etc.
};
return st[algo]; // assuming that `algo` goes from 0 to st.size()
}
如果真的需要一个函数指针,那么下面是如何声明一个返回函数指针的函数:
bool (*ChooseNext())(const RLS &, const RLS &)
{
// whatever
}
尽管使用std::function<bool(RLS const&, RLS const&)
有一些优势,但创建一个返回函数指针的函数是很有趣的。最简单但也最无聊的方法是使用typedef
:
typedef bool (*CompareFunction)(RLS const&, RLS const&);
CompareFunciton getFunction(int algo) {
switch (algo) {
case kAlgo1: return &SortFunc1;
case kAlgo2: return &SortFunc2;
default: assert("algo selection value out of range");
}
return &SortFunc1; // ... or somehow deal with the situation
}
好吧,我对实际函数的选择不感兴趣,只关心getFunction()
是如何声明的。很明显,有几种方法可以处理algo
超出范围的情况(assert()
,throw
,使用默认值,…)。
用typedef
可以做的事情也可以不用!因此,这里是不使用typedef
:的C++03版本
bool (*getFunction(int algo))(RLS const&, RLS const&) { ... }
好吧,这看起来很奇怪,但你可以把它看作是用实际的函数替换typedef。要阅读它是什么,你需要从右到左,从内到外阅读类型。不管怎样,温和地说,上述声明是可怕的。使用C++11可以使用尾随返回类型:
auto getFunction(int algo) -> bool(*)(RLS const&, RLS const&) { ... }
我认为,这种记法可读性很强。对函数指针使用尾随返回类型可以,但不一定能提高可读性,我认为(但我可能太老派了):
auto getFunction(int algo) -> auto (*)(RLS const&, RLS const&) -> bool { ... }
相关文章:
- QMetaObject invokeMethod的基于函数指针的语法
- C++-试图将函数指针推回到另一个CPP文件中的矢量时出错
- c++r值引用应用于函数指针
- 模板函数指针和lambda
- 是否可以将llvm::FunctionType转换为C/C++原始函数指针
- 带有类的函数指针
- () 函子后面的括号,而不是函数指针?
- 全局作用域中函数指针的赋值
- 使用"Task"函数指针队列定义作业管理器
- 将成员函数指针作为参数传递给模板方法
- 如何创建对象函数指针C++映射?
- 匹配函数指针作为模板参数?
- 通过函数指针定义类范围之外的方法
- 存储在类中的函数指针
- C++从函数指针数组调用函数
- 将返回值存储在函数指针数组的指针中是如何工作的?
- 整数键映射到头文件中的成员函数指针
- 从类成员函数到类 C 函数指针的转换
- 如何将内联匿名函数分配给C++函数指针
- 将字符缓冲区强制转换为函数指针