【问题标题】:boost::bind & boost::function with partial args带有部分参数的 boost::bind 和 boost::function
【发布时间】:2012-01-31 16:19:09
【问题描述】:

我给你发一个我想做的例子,这样更容易解释

    void myPrinter(const char* text, int number){            
            printf("\n%s %d\n", text, number);
        }

    int main() {

        char *someText="test";        

       boost::function<void(int my_number)> functionWithSavedArgs = boost::bind(&myPrinter, someText, ?????);

       //then I have to call my function with saved args and give to it only variable "number" like:
       int myBeautifulNumber = 2012;
       functionWithSavedArgs(myBeautifulNumber);
       // echo: test 2012
     }

有什么想法吗?

【问题讨论】:

    标签: c++ boost boost-bind boost-function


    【解决方案1】:

    跳过那个论点。

       boost::function<void(int my_number)> functionWithSavedArgs
            = boost::bind(&myPrinter, someText);
    

    这只会绑定第一个参数。

    如果您只想绑定第二个,则需要一个占位符:

       boost::function<void(int my_number)> functionWithSavedArgs
             = boost::bind(&myPrinter, _1, someNumber);
    

    【讨论】:

    • 我认为第一次绑定操作也应该使用占位符,例如:boost::bind(&myPrinter, someText, _1);
    • 我尝试编译不带占位符的部分绑定示例并遇到密集的编译器错误
    • 来自 Boost.bind 文档:In a bind(f, a1, a2, ..., aN) expression, the function object f must be able to take exactly N arguments. [...] int f(int, int); boost::bind(f, 1); // error, f takes two arguments。不幸的是,您不能省略参数并期望它们被占位符替换(与 std::bind 相同;我真的不知道为什么这是不可能的)。
    猜你喜欢
    • 1970-01-01
    • 2016-03-16
    • 1970-01-01
    • 1970-01-01
    • 2012-04-18
    • 1970-01-01
    • 2010-10-06
    • 2012-09-27
    • 1970-01-01
    相关资源
    最近更新 更多