Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass function by reference?

I have a C++ program that has free standing functions.

Since most of the team has little experience with or knowledge of object oriented design and programming, I need to refrain from function objects.

I want to pass a function to another function, such as for_each function. Normally, I would use a function pointer as a parameter:

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);
  }
}

I want to remove pointers since they can point to anywhere, and contain an invalid content.

Is there a method to pass a function by reference, similar to passing by pointer, without using function object?

Example:

  // 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);
like image 419
Thomas Matthews Avatar asked Mar 18 '23 12:03

Thomas Matthews


1 Answers

Just change your function pointer type to a function reference (* -> &):

typedef void (&P_String_Processor)(const std::string& text);
like image 71
Joseph Mansfield Avatar answered Mar 28 '23 18:03

Joseph Mansfield