简体   繁体   English

boost :: function参数的默认值?

[英]Default value for boost::function argument?

I've got a function that I want to take an optional boost::function argument as a callback for reporting an error condition. 我有一个函数,我想将一个可选的boost :: function参数作为报告错误条件的回调。 Is there some special value I can use a the default value to make it optional? 是否有一些特殊值我可以使用默认值使其可选?

For example, with a regular function pointer I can do: 例如,使用常规函数指针,我可以这样做:

void my_func(int a, int b, t_func_ptr err_callback=NULL) {

   if (error && (err_callback != NULL))
      err_callback();

}

Can I do something similar with boost::function replacing the function pointer? 我可以用boost :: function替换函数指针做类似的事吗?

You can use 0 (C++'s equivalent of NULL ) for the default value of a boost::function argument, which will result to an empty function object. 您可以使用0 (C ++相当于NULL )作为boost :: function参数的默认值,这将导致一个空函数对象。 You can test if it's empty by calling its empty() method, comparing it to 0, or simply using it in a boolean context: 您可以通过调用其empty()方法,将其与0进行比较,或者仅在布尔上下文中使用它来测试它是否为空:

void my_func(int a, int b, boost::function<void()> err_callback = 0) {
   if (error && err_callback)  // tests err_callback by converting to bool
      err_callback();
}

boost::function objects work pretty much like plain function pointers in this respect. boost::function对象在这方面与普通函数指针非常相似。

A good special value could be a default-constructed boost::function . 一个好的特殊值可能是默认构造的boost::function

An empty function evaluates false in a boolean context (like a NULL pointer), or you can use the empty() method to test if a function object wrapper actually contains a function. function在布尔上下文中评估false(如NULL指针),或者您可以使用empty()方法来测试函数对象包装器是否实际包含函数。 See the boost::function Tutorial . 请参阅boost :: function Tutorial

Here is a code sample: 这是一个代码示例:

#include <boost/function.hpp>
#include <iostream>

typedef boost::function<void (int code)> t_err_callback;

void do_callback(int code)
{
    std::cout << "Error " << code << std::endl;
}

void my_func(int a, int b, t_err_callback err_callback=t_err_callback())
{
    bool error = true;   // An error happened
    int error_code = 15; // Error code
    if (error && !err_callback.empty())
        err_callback(error_code);
}

int main()
{
    my_func(0, 0);
    my_func(0, 0, do_callback);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM