在函数中使用非静态值作为默认参数 [英] 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?
我想做的事情类似于
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屋!