如何通过引用传递函数?

时间:2014-09-11 16:37:07

标签: c++ function-pointers pass-by-reference function-object

我有一个具有独立功能的C ++程序。

由于大多数团队对面向对象的设计和编程缺乏经验或知识,我需要避免使用函数对象。

我想将函数传递给另一个函数,例如for_each函数。通常,我会使用函数指针作为参数:

typedef void (*P_String_Processor)(const std::string& text);
void For_Each_String_In_Table(P_String_Processor p_string_function)
{
  for (unsigned int i = 0; i < table_size; ++i)
  {
    p_string_function(table[i].text);
  }
}

我想删除指针,因为它们可以指向任何地方,并包含无效内容。

是否存在通过引用传递函数的方法,类似于通过指针传递,而不使用函数对象?

示例:

  // Declare a reference to a function taking a string as an argument.
  typedef void (??????);  

  void For_Each_String_In_Table(/* reference to function type */ string_function);

1 个答案:

答案 0 :(得分:7)

只需将函数指针类型更改为函数引用(* - &gt; &):

typedef void (&P_String_Processor)(const std::string& text);