Tho*_*ews 4 c++ function-pointers pass-by-reference function-object
我有一个具有独立功能的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);
}
}
Run Code Online (Sandbox Code Playgroud)
我想删除指针,因为它们可以指向任何地方,并包含无效的内容.
是否有一种通过引用传递函数的方法,类似于通过指针传递,而不使用函数对象?
例:
// 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);
Run Code Online (Sandbox Code Playgroud)
只需将函数指针类型更改为函数引用(*- > &):
typedef void (&P_String_Processor)(const std::string& text);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
171 次 |
| 最近记录: |