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