gpt4 book ai didi

c++ - 如何根据初始化参数修复类函数行为

转载 作者:行者123 更新时间:2023-12-04 08:25:13 24 4
gpt4 key购买 nike

我正在创建一个 C++ 类,它在初始化期间采用某些参数并具有一些基于其私有(private)变量的函数,例如 compute这里的功能:

class A {
public:
A(int x){
a = x;
}
int compute(int y){
if (a == 0){
return y*y;
}
else if (a == 1){
return 2*y;
}
else{
return y;
}
}
private:
int a;
};

// usage

A myA(1); // private variables set only once
myA.compute(10); // this will check value of a
myA.compute(1); // this will check value of a
鉴于私有(private)变量是在初始化期间设置的并且不会再次更改,有没有什么有效的方法可以避免在运行时与私有(private)变量相关的条件检查?
感谢您提供任何和所有帮助。谢谢

最佳答案

您可以在 int 上对函数 compute() 进行模板化,并将模板值用作参数。您可以在 https://godbolt.org/z/14Mh4E 查看结果

class A {
public:
A(int x) {
a = x;
}
template <int y>
constexpr int compute() const {
if (a == 0) {
return y * y;
}
else if (a == 1) {
return 2 * y;
}
else {
return y;
}
}
private:
int a;
};

// usage

A myA(1); // private variables set only once
myA.compute<10>(); // this will check value of a
myA.compute<1>(); // this will check value of a

关于c++ - 如何根据初始化参数修复类函数行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65300558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com