【问题标题】:C++ positional parametersC++ 位置参数
【发布时间】:2009-11-06 12:46:15
【问题描述】:

这是一个非常基本的问题,所以请多多包涵。

考虑 C++ 中的以下函数:

void foo(int a, int b, int c)
{
   //do something
}

我可以这样调用这个函数:foo(b=2, c=3, a=2) 吗?

我想这有某种名称(可能是位置参数)。如果您也可以在答案中澄清它,那就太好了。

【问题讨论】:

  • 当您有多个默认参数时,这是一种耻辱。幸运的是图书馆存在。

标签: c++ parameters


【解决方案1】:

不在标准 C++ 中,不。您必须按照函数原型指定的顺序提供参数。

【讨论】:

    【解决方案2】:

    使用核心 c++ 功能是不可能的。但是 boost 集合中有一个库使这成为可能。

    使用boost.parameters,您可以这样:

    #include <boost/graph/depth_first_search.hpp> // for dfs_visitor
    
    BOOST_PARAMETER_FUNCTION(
        (void), depth_first_search, tag
        …signature goes here…
    )
    {
       std::cout << "graph=" << graph << std::endl;
       std::cout << "visitor=" << visitor << std::endl;
       std::cout << "root_vertex=" << root_vertex << std::endl;
       std::cout << "index_map=" << index_map << std::endl;
       std::cout << "color_map=" << color_map << std::endl;
    }
    
    int main()
    {
        depth_first_search(1, 2, 3, 4, 5);
    
        depth_first_search(
            "1", '2', _color_map = '5',
            _index_map = "4", _root_vertex = "3");
    }
    

    【讨论】:

    • 虽然这个例子可以被翻译成 OP 例子...... +1 实际说明使用:)
    • 我认为这个解决方案是最好的
    【解决方案3】:

    我没有使用过 Boost 参数库,但获得这种东西的大部分好处的另一种方法是使用参数对象:

    struct fooParams {
        int a_;
        int b_;
        int c_;
        fooParams &a(int i) { a_ = i; return *this; }
        fooParams &b(int i) { b_ = i; return *this; }
        fooParams &c(int i) { c_ = i; return *this; }
        // can also provide a constructor, or other means of setting default values
    };
    
    void foo(fooParams params) { // or pass by const reference
        int a = params.a_;
        int b = params.b_;
        int c = params.c_;
        ...
    }
    
    fooParams params;
    foo(params.b(2).c(3).a(2));
    

    通过在参数对象中放置版本号、确保它是 POD 并通过指针传递,您可以同时执行 Microsoft 添加额外可选参数而不破坏二进制兼容性的事情。

    【讨论】:

    • 这是一个巧妙的“技巧”!这涉及到开销,但如果被调用的函数很重,那也没关系。
    【解决方案4】:

    在标准 C++ 中你不能。 如果您确实需要,请考虑使用Boost Parameter Library

    【讨论】:

      猜你喜欢
      • 2015-10-29
      • 1970-01-01
      • 2011-05-27
      • 2021-01-08
      • 2017-11-20
      • 1970-01-01
      • 2015-06-19
      • 2016-01-04
      相关资源
      最近更新 更多