开发者

C++ positional parameters

This is a very basic question, so please bear with me.

Consider the following function i开发者_运维问答n C++:

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

can I call this function like this: foo(b=2, c=3, a=2) ?

I suppose this have some sort of name (positional parameters, possibly). If you could clarify it in the answer too, it would great.


Not in standard C++, no. You'll have to provide the parameters in the order specified by the function prototype.


It's not possible using the core c++ features. But there is a library in the boost collection that makes this possible.

With boost.parameters you can for example this:

#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");
}


I've not used the Boost parameter library, but another way to get most of the benefits of this kind of thing is with parameter objects:

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));

You can simultaneously do the Microsoft thing of adding extra optional parameters without breaking binary compatibility, by putting a version number in the parameter object, making sure it's POD, and passing by pointer.


In standard C++ you can't. Consider using Boost Parameter Library if you really need this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜