【问题标题】:Boost.Fusion Functional: Calling functions with default argumentsBoost.Fusion Functional:使用默认参数调用函数
【发布时间】:2010-08-21 12:35:09
【问题描述】:

是否可以使用boost::fusion::invoke 函数来调用具有默认参数而不指定默认参数的函数?

Example:

void foo(int x, int y = 1, int z = 2)
{
  std::cout << "The sum is: " << (x + y + z) << std::endl;
}

...

// This should call foo(0). It doesn't work because the type of foo is void (*) (int, int, int).
boost::fusion::invoke(foo, boost::fusion::vector<int>(0));

// Works
boost::fusion::invoke(foo, boost::fusion::vector<int, int, int>(0, 1, 2));

我正在编写一个用于绑定到脚本语言的包装器,默认参数将极大地改善包装器用户的直观感受。恐怕标准并没有涵盖这种情况。

附注:
我知道可以使用仿函数来解决它:

struct foo  {
  void operator() (int x, int y = 1, int z = 2)  { /* ... */ }
};

// Works because the functor adds an indirection
boost::fusion::invoke(foo(), boost::fusion::vector<int>(0));

但这不是一个选项,因为我不想强迫用户创建函子只是为了指定默认参数。

【问题讨论】:

    标签: c++ function metaprogramming function-pointers boost-fusion


    【解决方案1】:

    您可以使用bind (more info):

    boost::fusion::invoke(boost::bind(foo, _1, 1, 2), boost::fusion::vector<int>(0));
    

    【讨论】:

    • 谢谢,这似乎是一个合理的解决方案。我对直接在函数声明中指定默认参数更感兴趣,但似乎根本不可能将它们与 invoke() 结合起来。
    猜你喜欢
    • 2012-06-14
    • 2012-11-20
    • 2017-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-28
    • 2017-10-23
    • 2013-04-26
    相关资源
    最近更新 更多