tags:

views:

108

answers:

4

Hi.

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

Consider the following function in C++:

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

can I call this funtion 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.

Thanks.

+7  A: 

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

Timo Geusch
+1  A: 

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

begray
+5  A: 

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");
}
Joakim Karlsson
Although the example could have been translated into the OP example... +1 for actually illustrating the use :)
Matthieu M.
I'm thinking that this solution is the best
Davit Siradeghyan
A: 

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.

Steve Jessop