使用非静态值作为函数中的默认参数
Using a non static value as default argument in a function
有没有一种很好的方法可以将非静态值作为函数中的默认参数?我见过一些对同一问题的较早的回答,这些回答总是以明确写出过载而告终。这在 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
}
}
这使得过载的目的不那么明显。
一种相对优雅的方法(在我看来(是使用 std::optional
来接受参数,如果没有提供参数,请使用对象的默认值:
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 小节描述了成员访问(摘录(:
非静态成员不得出现在默认参数中,除非 显示为类成员访问表达式的 ID 表达式 (8.5.1.5( 或除非它用于形成指向成员的指针 (8.5.2.1).[示例:在以下示例中 X::mem1(( 的声明 格式不正确,因为没有为非静态提供对象 memberX::a 用作初始值设定项。
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;
};
相关文章:
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- 无法将类对象转换为函数默认参数中的参考
- 如何使类的函数默认
- C++ 定义函数默认参数的正确方法
- 函数默认参数被忽略
- 构造函数默认公共和私有变量
- C++11 不生成特殊函数/默认构造函数
- 类模板构造函数默认参数
- 模板函数默认参数
- 重新声明时替换函数默认参数
- 模板函数默认参数和类型推断
- 构造函数默认参数
- C++模板构造函数默认参数
- 为什么内联函数默认情况下具有外部链接
- 在c++中设置构造函数默认值
- 虚函数默认参数和重载
- 指针对成员函数默认值出现与CRTP相关的编译器错误
- c++构造函数默认参数
- 名称空间中的两个对象将由不同的函数默认初始化,并由名称空间中的类使用
- C++中的函数默认参数