views:

64

answers:

4

Hi,

I have thread spawning function which accepts many parameters which have default values in the declaration.

int spawn( funcptr func, void *arg = 0,int grp_id = 1,const char*threadname);

I want to initialize first parameter func and the last parameter thread name and remaining variables assigned their default values.

spawn( myfunc,"My Thread");

How can I do this.

A: 

This is not possible in C++, once you assign a default value for a parameter all subsequent parameters should also have default parameters. Only option is to rearrange the parameters so that all the parameters for which default values can be assigned comes at the end.

Naveen
+5  A: 

You can't.

Other languages support things like spawn(myfunc, , , "MyThread"), but not C++.

Instead, just overload it to your liking:

inline int spawn( funcptr func, const char*threadname) {
    return spawn(func, 0, 1, threadname);
}
Gunslinger47
+1  A: 

The other answers are technically correct, but it is possible to do this, using the Boost.Parameter library. It requires quite a bit of setup though, and may or may not be worth it for you.

Head Geek
+1  A: 

From here,

Parameters with default arguments must be the trailing parameters in the function declaration parameter list.

For example:

void f(int a, int b = 2, int c = 3);  // trailing defaults
void g(int a = 1, int b = 2, int c);  // error, leading defaults
void h(int a, int b = 3, int c);      // error, default in middle

So if you are the one who is declaring and defining your spawn() function, you can have the defaults at the end.. And the other way round is not possible..

liaK