简体   繁体   English

使用函数的默认值分配参数

[英]Parameters assignment with default values for a function

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); 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. 我想初始化第一个参数func和最后一个参数线程名称和剩余变量分配它们的默认值。

spawn( myfunc,"My Thread"); spawn(myfunc,“My Thread”);

How can I do this. 我怎样才能做到这一点。

You can't. 你不能。

Other languages support things like spawn(myfunc, , , "MyThread") , but not C++. 其他语言支持spawn(myfunc, , , "MyThread") ,但不支持C ++。

Instead, just overload it to your liking: 相反,只是根据自己的喜好重载它:

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

The other answers are technically correct, but it is possible to do this, using the Boost.Parameter library. 其他答案是技术上是正确的,但可能做到这一点,利用Boost.Parameter库。 It requires quite a bit of setup though, and may or may not be worth it for you. 它需要相当多的设置,并且可能或可能不值得你。

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.. 因此,如果您是声明和定义spawn()函数的人,那么您可以在结尾处使用默认值。而另一种方法是不可能的..

This is not possible in C++, once you assign a default value for a parameter all subsequent parameters should also have default parameters. 这在C ++中是不可能的,一旦为参数指定了默认值,所有后续参数也应该具有默认参数。 Only option is to rearrange the parameters so that all the parameters for which default values can be assigned comes at the end. 唯一的选择是重新排列参数,以便最后可以分配所有可以分配默认值的参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM