gpt4 book ai didi

c++ - Cpp中的动态功能

转载 作者:行者123 更新时间:2023-12-02 10:18:05 24 4
gpt4 key购买 nike

我一直在从事cpp项目,我想动态地实现我的功能。
运行时,我有一个具有回合9个选项的函数。

将大写字母作为条件作为 bool(boolean) 类型,将小写字母作为函数。并假设我的函数在全局函数范围之外具有其条件(A-I)。而且条件在运行期间不会更改。只能在运行此功能之前将其设置一次,并且在此功能期间不会更改。

void Myfunction(){
if(A) a(); // I would not use else if or switch since I should check all conditions.
if(B) b();
...
if(I) i();
return;
}

并且该函数将以无限循环的方式被调用
int main(void){
//Conditions A - I is declared here
while (1) Myfunction;
return 0;
}

我确实知道使用if语句的速度很慢,并且检查非可变条件也是一种废话。为了在运行此功能时节省计算资源并节省时间,我想动态创建功能。这意味着如果首先检查其条件(A-I),则该函数将决定要使用的表达式。

例如,如果我们有条件A,B,C为真,而所有其他条件(D-I)为假。
我想使该功能自动变为。
void Myfunction(){
a();
b();
c();
return;
}

我已经搜索了互联网,但找不到任何内容。
我在cpp中找到了一些有关模板的文章,但事实并非如此。

感谢您阅读本文。
由于我是Stackoverflow的新手,因此我可能在本文中犯了一些错误。
如果这篇文章中有任何违反Stackoverflow规则的内容,请告诉我。我很乐意修改我的帖子。

谢谢。

最佳答案

我试图使用功能模板创建解决方案。

两个主要功能是GetMyFunction()MyFunctionTemplate()
MyFunctionTemplate()是一个函数模板,它将接受所有期望的参数作为bool模板参数(非类型的模板参数)。
GetMyFunction()函数将在运行时返回指向MyFunctionTemplate()所需的特殊化的指针。
GetMyFunction()还要做一件事,它必须检查所有参数组合,并返回相应的函数。

这些MyFunctionTemplate()专门化将在编译时创建,并且我相信MyFunctionTemplate()中的那些if()检查将被删除,因为这些是时间编译时常量(请确保这一点)。

#include <iostream>

using namespace std;

void aFunc() { cout << "in a()" << endl; }
void bFunc() { cout << "in b()" << endl; }
void cFunc() { cout << "in c()" << endl; }
void dFunc() { cout << "in d()" << endl; }

template <bool a, bool b, bool c, bool d>
void MyFunctionTemplate()
{
if (a) aFunc();
if (b) bFunc();
if (c) cFunc();
if (d) dFunc();
}

void (*GetMyFunction(bool a, bool b, bool c, bool d))()
{
if (a && b && c && d)
return &MyFunctionTemplate<true, true, true, true>;
if (a && b && c && !d)
return &MyFunctionTemplate<true, true, true, false>;
// And all other combinations follows....
}

int main(void)
{
// Conditions A - I is declared here
bool a = true, b = true, c = true, d = true;
// auto MyFunction = GetMyFunction(a, b, c, d);
void (*MyFunction)(void) = GetMyFunction(a, b, c, d);
MyFunction();

return 0;
}

关于c++ - Cpp中的动态功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61284265/

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