将内联回调函数指定为参数

4

首先,让我使用一些伪代码(JavaScript)来解释我想要实现的目标。

// Declare our function that takes a callback as as an argument, and calls the callback with true.
B(func) { func(true); }

// Call the function
B(function(bool success) { /* code that uses success */ });

我希望这已经说明了一切。如果还有不清楚的地方,请在我的问题下评论,以便我可以写更多内容来澄清我的问题。

我的要求是在C++中使用像这样的代码。

我尝试使用lambda函数,但我无法为其指定参数类型。

2个回答

5
如果你的编译器是比较新的版本(如Visual Studio 2010或GCC 4.5),你可以使用一些新的C++标准特性,该标准目前正在批准中,并应很快发布。
我不知道在Visual Studio中启用此功能需要做什么,但应该会在MSDN或内部帮助文档中有详细说明。
对于GCC 4.5,只需添加 -std=c++0x 选项即可启用新特性。
其中之一的特性是Lambda语法: Lambda函数和表达式:
template <typename F>
void func_with_callback(F f) {
    f(true);
}

int main() {
    func_with_callback( [](bool t){ if(t) cout << "lambda called" << endl; } );
}

如果您无法使用现代编译器,可以使用函数对象和类似boost::lambda的库实现类似的功能。

这正是我一直在寻找的。我已经尝试过模板和lambda表达式,但无法使其工作。顺便说一下,VS2010可以在不进行任何其他更改的情况下使用它。 - user215361
我想要保存函数参数(在这种情况下是 f)以备后用,我该怎么做? - Issung
@Joel 使用 std::function - greyfade

3

编辑:再次阅读您的问题后,看起来您可能正在寻找C++中的匿名函数。如果是这样,不幸的是,该语言目前不支持此功能。在这种情况下,C++需要更加详细地描述这些内容。如果您需要比boost::lamda提供的更多内容,则应将其分离为普通函数。


在C和C++中,可以使用函数指针或函数对象(仅限于C++)和模板来实现此操作。

例如(使用C++方式(函数对象))

//Define a functor. A functor is nothing but a class which overloads
//operator(). Inheriting from std::binary_function allows your functor
//to operate cleanly with STL algorithms.
struct MyFunctor : public std::binary_function<int, int, bool>
{
    bool operator()(int a, int b) {
        return a < b;
    };
};

//Define a template which takes a functor type. Your functor should be
//should be passed by value into the target function, and a functor should
//not have internal state, making this copy cheap.
template <typename Func_T>
void MyFunctionUsingACallback(Func_T functor)
{
    if (functor(a, b))
        //Do something
    else
        //Do something else
}

//Example usage.
int main()
{
    MyFunctionUsingACallback(MyFunctor());
}

使用C语言的方式(函数指针):

//Create a typedef for a function pointer type taking a pair of ints and
//returning a boolean value.
typedef bool (*Functor_T)(int, int);

//An example callback function.
bool MyFunctor(int a, int b)
{
    return a < b;
}

//Note that you use the typedef'd function here.
void MyFunctionUsingACallback(Functor_T functor)
{
    if (functor(a, b))
        //Do something
    else
        //Do something else
}

//Example usage.
int main()
{
    MyFunctionUsingACallback(MyFunctor);
}

注意,你应该更倾向于使用C++的方法,因为这将允许编译器在内联方面做出更明智的决策,除非由于某些原因你只能使用C子集。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接