代码之家  ›  专栏  ›  技术社区  ›  user215361

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

  •  3
  • user215361  · 技术社区  · 14 年前

    首先,让我解释一下使用一些伪代码(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 回复  |  直到 11 年前
        1
  •  2
  •   greyfade    14 年前

    如果编译器是最近发布的版本(例如VisualStudio 2010或GCC 4.5),则可以使用新C++标准中的一些新特性,该标准目前正在批准中,并应尽快发布。

    我不知道要在Visual Studio中启用它需要做什么,但它应该在msdn或内部帮助中有良好的文档记录。

    对于GCC4.5,只需添加 -std=c++0x 启用新功能的选项。

    其中一个功能是 Lambda syntax :

    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)之类的技术,这些技术也可以执行类似的操作。

        2
  •  3
  •   Billy ONeal IS4    14 年前

    编辑:在再次阅读您的问题后,看起来您可能正在寻找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子集。