在函数中使用非静态值作为默认参数 [英] Using a non static value as default argument in a function
问题描述
是否有一种很好的方法可以将非静态值作为函数中的默认参数?我看到过对同一问题的一些较旧的回答,这些回答总是以明确写出重载而告终.这在 C++17 中还有必要吗?
Is there a nice way to have a non static value as default argument in a function? I've seen some older responses to the same question which always end up in explicitly writing out the overload. Is this still necessary in C++17?
我想做的是做一些类似的事情
What I'd like to do is do something akin to
class C {
const int N; //Initialized in constructor
void foo(int x = this->N){
//do something
}
}
而不必写
class C {
const int N; //Initialized in constructor
void foo(){
foo(N);
}
void foo(int x){
//do something
}
}
这使得重载的目的不那么明显.
which makes the purpose of the overload less obvious.
推荐答案
一种相对优雅的方式(在我看来)是使用 std::optional
来接受参数,如果没有参数提供,使用对象的默认值:
One relatively elegant way (in my opinion) would be to use std::optional
to accept the argument, and if no argument was provided, use the default from the object:
class C {
const int N_; // Initialized in constructor
public:
C(int x) :N_(x) {}
void foo(std::optional<int> x = std::nullopt) {
std::cout << x.value_or(N_) << std::endl;
}
};
int main() {
C c(7);
c.foo();
c.foo(0);
}
您可以在标准的第 11.3.6 节中找到有关哪些有效/无效的完整说明.第 9 小节描述了成员访问(摘录):
You can find the full explanation of what works/doesn't work in section 11.3.6 of the standard. Subsection 9 describes member access (excerpt):
非静态成员不应出现在默认参数中,除非它显示为类成员访问表达式的 id 表达式(8.5.1.5) 或者除非它用于形成指向成员的指针(8.5.2.1).[示例:下例中X::mem1()的声明格式错误,因为没有为非静态提供对象memberX::a 用作初始化器.
A non-static member shall not appear in a default argument unless it appears as the id-expressionof a class member access expression (8.5.1.5) or unless it is used to form a pointer to member (8.5.2.1).[Example:The declaration of X::mem1()in the following example is ill-formed because no object is supplied for the non-static memberX::a used as an initializer.
int b;
class X {
int a;
int mem1(int i = a);// error: non-static memberaused as default argument
int mem2(int i = b);// OK; useX::b
static int b;
};
这篇关于在函数中使用非静态值作为默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!