4

我有一个具有独立功能的 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);
4

1 回答 1

7

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

typedef void (&P_String_Processor)(const std::string& text);
于 2014-09-11T16:41:59.290 回答