“变量"变量名c ++ [英] "Variable" variable names c++

查看:148
本文介绍了“变量"变量名c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我在这里搜索了一段时间,以寻找一种方法来遍历名为 variable_1 variable_2 ,...., variable_n .基本上,我在问是否有一种方法可以使用循环来实现 variable_i ,或更具体地,在我的案例中,是实现 functionName_i .

The Problem: I've been searching on here for a while looking for a way to loop through variables named somewhat like variable_1, variable_2, ...., variable_n. Basically, I'm asking if there's a way to do that using a loop to achieve variable_i or, more specifically in my case, functionName_i.

我需要的:我试图循环对象的数组以调用顺序命名并与对象的数组平行的不同函数(即:obj [i]-> callback_i())

What I need: I'm trying to loop an objects' array to call different functions which are sequentially-named and parallel to the objects' array ( i.e: obj[ i ]->callback_i( ) )

我所知道的:很显然,这里的答案(如果只是变量)是使用数组或向量.但是,如果可能的话,我只需要按顺序将函数的名称连接起来即可.

What I Know: Obviously, the answer here (if it were just variables) is using an array or vector. However, I need to just concatenate the functions' names sequentially somehow if it's possible.

可能的解决方法:我想到的一切都可以回溯到创建函数指针的数组/向量.如果我真的没有选择的余地,我可能会最终使它工作,但我只是出于好奇而问.

Possible Workarounds: Everything I think of goes back to creating an array/vector of function pointers. I might get it eventually to work if I'm really out of options, but I just thought I should ask out of curiosity.

清除问题:是否有一种方法可以使用变量int i 作为函数名称的一部分来遍历顺序命名的函数?

Clear Question: Is there a way to loop through sequentially-named functions using a variable int i as part of the functions' names?

谢谢!

推荐答案

否.

C ++通常在运行时不存储类型或变量名称信息.如果是这样,它就不是可移植的( typeid()在编译器之间确实有所不同),或者根本不可能.您不能在运行时引用变量名,除非您使系统能够执行此类操作,或者使用调试信息(这不是标准的C ++功能).

No.

C++ does not usually store type or variable name information at runtime; if it does, it's not portable (typeid() does vary across compilers) or it's just not possible. You can't reference a variable name at runtime unless you make a system to do that sort of thing, or you use debugging information, which isn't a standard C++ feature.

这种类型的反射很昂贵,并且更适合于高级语言.C ++是一种较低级的语言,它剥夺了糖,只是告诉您不".

This type of reflection is expensive and is more suited towards higher-level languages. C++, as a more lower-level language, strips off the sugar and just tells you "no."

如果创建命名系统,则可以在C ++中创建这种类型的东西,但是广义的命名系统还需要变体, NULL/Maybe 惯用语的版本,属性,检查以及许多其他内容.调试,并且您可以根据需要进行所有操作,但这是您最好切换到另一种已找到所需答案的语言并将C ++绑定到该语言的地方.

You can make this type of thing in C++ if you make a naming system, but a generalized one would also require variants, a version of the NULL/Maybe idiom, attributes, checks, lots of debugging and you can do it all if you wish, but this is where you might as well switch to another language that already has the answer you're looking for and bind C++ to it.

或者,使用函数的矩阵或数组. 然后,按索引进行迭代.

Alternatively, use a matrix or array of functions. Then, iterate by index.

这篇关于“变量"变量名c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆