Arn*_*rah 14 c++ language-construct default-value c++11
假设我有这样的代码:
void f(int a = 0, int b = 0, int c = 0)
{
//...Some Code...
}
Run Code Online (Sandbox Code Playgroud)
正如您可以在上面看到我的代码,参数a,b以及c默认参数值为0.现在看看我的主要功能如下:
int main()
{
//Here are 4 ways of calling the above function:
int a = 2;
int b = 3;
int c = -1;
f(a, b, c);
f(a, b);
f(a);
f();
//note the above parameters could be changed for the other variables
//as well.
}
Run Code Online (Sandbox Code Playgroud)
现在我知道我不能只跳过一个参数,并让它具有默认值,因为该值将作为该位置的参数进行评估.我的意思是,我不能,比如说f(a,c),因为,c将被评估为b,这是我不想要的,特别是如果c是错误的类型.有没有一种方法让调用函数在C++中指定,在任何给定的位置使用函数的任何默认参数值,而不限于从最后一个参数向后转到无?是否有任何保留关键字来实现这一目标,或者至少是解决方法?我可以给出一个例子:
f(a, def, c) //Where def would mean default.
Run Code Online (Sandbox Code Playgroud)
Ale*_*dro 15
对此没有保留字,f(a,,c)也无效.你可以省略一些最右边的可选参数,如你所示,但不能省略那样的中间可选参数.
http://www.learncpp.com/cpp-tutorial/77-default-parameters/
直接从上面的链接引用:
多个默认参数
一个函数可以有多个默认参数:
Run Code Online (Sandbox Code Playgroud)void printValues(int x=10, int y=20, int z=30) { std::cout << "Values: " << x << " " << y << " " << z << '\n'; }给出以下函数调用:
Run Code Online (Sandbox Code Playgroud)printValues(1, 2, 3); printValues(1, 2); printValues(1); printValues();生成以下输出:
Run Code Online (Sandbox Code Playgroud)Values: 1 2 3 Values: 1 2 30 Values: 1 20 30 Values: 10 20 30请注意,如果不提供x和y的值,则无法为z提供用户定义的值.这是因为C++不支持函数调用语法,例如printValues(,, 3).这有两个主要后果:
1)所有默认参数必须是最右边的参数.以下是不允许的:
Run Code Online (Sandbox Code Playgroud)void printValue(int x=10, int y); // not allowed2)如果存在多个默认参数,则最左边的默认参数应该是用户最可能明确设置的参数.
Jar*_*d42 10
作为解决方法,您可以(ab)使用boost::optional(直到std::optional从c ++ 17开始):
void f(boost::optional<int> oa = boost::none,
boost::optional<int> ob = boost::none,
boost::optional<int> oc = boost::none)
{
int a = oa.value_or(0); // Real default value go here
int b = ob.value_or(0); // Real default value go here
int c = oc.value_or(0); // Real default value go here
//...Some Code...
}
Run Code Online (Sandbox Code Playgroud)
然后打电话给它
f(a, boost::none, c);
Run Code Online (Sandbox Code Playgroud)
不完全是你问的,但你可以std::bind()用来修复参数的值.
有些想法
#include <functional>
void f(int a = 0, int b = 0, int c = 0)
{
//...Some Code...
}
int main()
{
//Here are 4 ways of calling the above function:
int a = 2;
int b = 3;
int c = -1;
f(a, b, c);
f(a, b);
f(a);
f();
//note the above parameters could be changed for the other variables
//as well.
using namespace std::placeholders; // for _1, _2
auto f1 = std::bind(f, _1, 0, _2);
f1(a, c); // call f(a, 0, c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
随着std::bind()您可以修复的参数值从默认参数值不同或值而不默认值.
std::bind()仅考虑C++ 11中提供的计数.
ps:抱歉我的英语不好.
| 归档时间: |
|
| 查看次数: |
4561 次 |
| 最近记录: |