“Variable” variable names c++

二次信任 提交于 2021-02-07 19:56:38

问题


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.

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.

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

Thanks!


回答1:


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.

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."

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.



来源:https://stackoverflow.com/questions/31888969/variable-variable-names-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!