如何在不使用 "if" 的情况下编写 return 值取决于标志的函数?
How to program a function whose return value is depending on the flag without using "if"?
我想制作一个类似于下面概念代码的class函数。
double function(){
if(flag==true){
"some process and return "
}
else{
"another process and return"
}
}
其中 flag
是 class 的布尔成员。
我想在不使用 if
的情况下创建此功能,因为我多次使用此功能。
分数是
- 我想在流程的两个案例中使用相同的功能。
- 我想避免重新评估在一段时间内不会更改其值的标志。
您可以将布尔值转换为 int
int test(bool flag)
{
return static_cast<int>(flag);
}
int not_test(bool flag)
{
return static_cast<int>(!flag);
}
备注:到发布此答案时,问题已完全不同。
Class 函数、标志和两种不同的行为?您可能应该制作两个派生的 类,删除标志,并改用 virtual
函数。
如果你想根据 bool
的值调用两个不同的成员函数之一,而不使用 if
或其他可能导致分支的东西,你可以创建一个 table 包含两个函数指针,并使用 bool
进行索引查找。如果您只想在标志值更改时执行此查找,您可以存储指向 active 函数的指针,并且仅在设置 flag
时执行查找。
成员函数也接受参数的示例:
#include <iostream>
class foo {
public:
using func_t = double(foo::*)(double); // the type of the member functions
double some(double x) { return x * 3.14159; }
double another(double x) { return x * 3.14159 * 3.14159; }
double function(double x) {
return (this->*active)(x); // "active" only changes when "flag" is set
}
void set(bool x) {
flag = x;
// lookup without "if" to set the active function:
active = funcs[flag];
}
private:
// a static table of the functions to be called - only initialized once
static constexpr func_t funcs[]{&foo::some, &foo::another};
bool flag = false;
func_t active = &foo::some; // the active function
};
int main() {
foo x;
x.set(false);
std::cout << x.function(2.) << '\n';
x.set(true);
std::cout << x.function(3.) << '\n';
}
输出
6.28318
29.6088
我想制作一个类似于下面概念代码的class函数。
double function(){
if(flag==true){
"some process and return "
}
else{
"another process and return"
}
}
其中 flag
是 class 的布尔成员。
我想在不使用 if
的情况下创建此功能,因为我多次使用此功能。
分数是
- 我想在流程的两个案例中使用相同的功能。
- 我想避免重新评估在一段时间内不会更改其值的标志。
您可以将布尔值转换为 int
int test(bool flag)
{
return static_cast<int>(flag);
}
int not_test(bool flag)
{
return static_cast<int>(!flag);
}
备注:到发布此答案时,问题已完全不同。
Class 函数、标志和两种不同的行为?您可能应该制作两个派生的 类,删除标志,并改用 virtual
函数。
如果你想根据 bool
的值调用两个不同的成员函数之一,而不使用 if
或其他可能导致分支的东西,你可以创建一个 table 包含两个函数指针,并使用 bool
进行索引查找。如果您只想在标志值更改时执行此查找,您可以存储指向 active 函数的指针,并且仅在设置 flag
时执行查找。
成员函数也接受参数的示例:
#include <iostream>
class foo {
public:
using func_t = double(foo::*)(double); // the type of the member functions
double some(double x) { return x * 3.14159; }
double another(double x) { return x * 3.14159 * 3.14159; }
double function(double x) {
return (this->*active)(x); // "active" only changes when "flag" is set
}
void set(bool x) {
flag = x;
// lookup without "if" to set the active function:
active = funcs[flag];
}
private:
// a static table of the functions to be called - only initialized once
static constexpr func_t funcs[]{&foo::some, &foo::another};
bool flag = false;
func_t active = &foo::some; // the active function
};
int main() {
foo x;
x.set(false);
std::cout << x.function(2.) << '\n';
x.set(true);
std::cout << x.function(3.) << '\n';
}
输出
6.28318
29.6088