4

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);
Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154
  • 1
    "...most of the team has little experience with or knowledge of object oriented design and programming..." - kind of revelation rarely seen among programmers in C++ :)) – SChepurin Sep 11 '14 at 16:53
  • @SChepurin: Most of the team are C programmers. – Thomas Matthews Sep 11 '14 at 17:55
  • another option would be skipping the typedef all together and using `template void For_Each_String_In_Table( T& stringFunc )` but might lead to discussion between the 'generic' and 'it's not clear' camps – stijn Sep 11 '14 at 18:16
  • 1
    @Thomas Matthews - "Most of the team are C programmers." - never thought that for C programmers function objects are less OOP oriented than templates. – SChepurin Sep 11 '14 at 18:37

1 Answers1

7

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

typedef void (&P_String_Processor)(const std::string& text);
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324
  • Isn't the `&P_String_Processor` parsed as the address of the function? – Thomas Matthews Sep 11 '14 at 16:43
  • @ThomasMatthews Nope. `&` has different meanings depending on the context. In a type, `&` means "reference". In an expression, `&` means "address of". In this case, it's certainly not an expression. It's part of the type. – Joseph Mansfield Sep 11 '14 at 16:44
  • Please include an example of calling the function reference. – Thomas Matthews Sep 11 '14 at 16:44
  • @ThomasMatthews Calling a reference to a function is exactly the same as calling a pointer to a function. – David G Sep 11 '14 at 16:45
  • `typedef int (&a)(void); typedef int (*b)(void); a x = foo; b y = foo; b y1 = &foo; int res1 = x(); int res2 = y(); a z = *y; b zz = &x;` – IdeaHat Sep 11 '14 at 16:47