PDA

View Full Version : Re: QString to variable name?



shokarta
9th January 2020, 09:25
Hello gurus,

lets say I have this:


terminal_db_array["dbname"] = "something"

QString first = 'terminal_db';
QString second = '_array["driver"]';

and I want to check if the variable exists when i join those two strings together:
if ({first+second}=="something")

d_stranz
9th January 2020, 17:48
What you are asking for is something called "reflection", the ability to retrieve metadata about the variables and types defined in a program. It doesn't exist in C++.

Here are two links, one a blog post (https://preshing.com/20180116/a-primitive-reflection-system-in-cpp-part-1/) and the other an answer to a stackoverflow question (https://stackoverflow.com/questions/41453/how-can-i-add-reflection-to-a-c-application). I do not know if either of these solutions will allow you to retrieve the name of the variable that instantiates a type or just lets you get at the type itself.

Qt types derived from QObject implement a meta-object system that allows you to identify the types and classnames of QObject instances at runtime. It doesn't permit you to identify the names of the actual C++ variables that represent instances of those classes, but because you can use QObject::setObjectName() to give a unique name to each QObject instance, you could use this feature to give each of your QObject instances the same name as the variable that instantiates it.

The Java language has reflection built in, through the java.lang.reflect package.

ChrisW67
10th January 2020, 23:41
Depending on the specific requirements you could use a different data structure to achieve this goal without reflection. Essentially move the compile-time item terminal_db_array (and the others like it) into run-time data.