如何通过引用传递函数?

托马斯·马修斯

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

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

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

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);
约瑟夫·曼斯菲尔德

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章