函数返回C++11中的函数指针

Function returning function pointer in C++11

本文关键字:函数 指针 C++11 返回      更新时间:2023-10-16

我有以下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 { ... }