Accessing a class member variable by its name at runtime [duplicate] - c++

This question already has answers here:
Get attribute by name
(5 answers)
Closed 4 years ago.
In the vein of more impossible-but-is-it-really questions:
Is it possible to access the member variable of a class, where the variable's name is stored in a string?
class Test
{
public:
int test = 0;
}
string name = "test"; // let's assume we know test is an int.
Any chance of getting the value of test, using the string?
One bit of cheating not allowed:
enum vartype {
INT,
..
}
No forcing the class to register all its variables in a std::map<string, std::pair<vartype, void*> >.
All other tricks welcome.
Thanks!

No.
To do this, you need to provide some mapping between member variables and the string names by which you intend to access them.

In the realm of really ugly kluges, you could build the program with debug information and have it use that to find the location of the variable in the same way a debugger would. But other than that, you're out of luck. C++ doesn't do reflection.

About why it's not available in C++ and an alternative: http://en.allexperts.com/q/C-1040/eval-function-javascript-C.htm
It's possible in MATLAB though...
As a very simple example, if you have a matrix updation to do, which goes like:
M1=1;
M2=2;
M3=3;
And you would prefer that the variable names could be altered so that you could use a for loop, then it can also be done this way:
for i=1:3
eval(['M' num2str(i) '=' num2str(i)]);
end
I used to do this in Actionscript. Was really glad to find that it's available in Matlab too

Related

When and why would I use a constant function in C++ [duplicate]

This question already has answers here:
Why use a const member function?
(3 answers)
What are the semantics of a const member function?
(9 answers)
Closed 2 months ago.
This post was edited and submitted for review 2 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Edit: From #Jeremy Friesner's answer, he provides another view point that Why use a const member function & semantics of a const member function don't cover. It can improve clarity and disambiguous your code. People can have a brief idea of what this function is supposed to do or not do at the first glance. Very useful especially in working with others.
I come across the constant function lately.
It says:
Constant functions are those have denied permission when attempting
to change the member variables of their classes.
My questions are
In a programmer perspective, if you don't want a function being able to change member
variables, why not just moving the parts responsible for changing variables outside
of the function at the first place? (e.g using another function)
What/when are some practical moments of having the neediness to use a constant
function?
Appreciate any answers
class Foo
{
public:
int x = 0;
int Bar(int arg) const
{
x++; // fails
return x; // okay
}
};
The purpose of const-tagged methods isn't to prevent the programmer from intentionally modifying member variables, but rather to allow the compiler to assist the programmer by producing a compile-time error when the programmer accidentally modifies a member-variable. This is useful because it's much easier and quicker to correct a compile-time error than to chase down a run-time misbehavior through manual testing.
The const tag also assists later programmers who are reading the class's header file by helping them quickly understand what a method does or does not do. For example, if you see this in a class declaration:
class MyClass
{
[...]
int CalculateTheValue();
... you might ask yourself, "does calling CalculateTheValue() change the state of the MyClass object?" With a name like CalculateTheValue() it seems like it shouldn't, but there's no way to know for sure without finding the corresponding .cpp file and reading through the code that implements that method... which is a tedious and error-prone way to do things.
On the other hand, if you see this:
class MyClass
{
[...]
int CalculateTheValue() const;
... then you know right away that CalculateTheValue() will not modify the MyClass object you call it on, because it says so in the declaration. (if it did try to modify the MyClass object, the code wouldn't compile; so if the code compiled, we know it doesn't modify it)

Is there a way of seeing if user input matches variable name in c++? [duplicate]

This question already has answers here:
Convert string to variable name or variable type
(7 answers)
Closed 6 years ago.
If the title was not clear, I will try to clarify what I am asking:
Imagine I have a variable called counter, I know I can see its current value by doing something like:
std::cout << counter << std::endl;
However, assume I have lots of variables and I don't know which I'm going to want to look at until runtime.
Does anyone know a way I can fetch the value of a variable by using its name, for example:
std::cout << valueOf("counter") << std::endl;
I feel being able to do this might make debugging large complex projects easier.
Thanks in advance for your time.
Update: All the answers provided are valid and useful, however the main point is that reflection does not exist in C++ (and after reading the link recommended it is clear why).
As has been mentioned, you are looking for reflection in C++. It doesn't have that, and this answer explains why.
You can use an associative container as a std::map< std::string, your_variable_type > to link a string to a variable, assuming they are all of the same type.
If you have variable of different types, solution exists, as in boost::variant
No, not with C++ or its standard library. Of course, you can hack something up to emulate this behaviour. C++ allows you to choose methods at runtime, using polymorphism, so you can take advantage of that. In essence, you'll get the method to invoke at runtime, rather than the variable, and the method will return the vlaue:
struct Value {
virtual ~Value();
virtual std::string value() const = 0;
};
struct Counter : public Value {
int v;
std::string value() const {
istringstream ss(v);
return ss.str();
}
};
struct Mounter : public Value {
double v;
std::string value() const {
istringstream ss(v);
return ss.str();
}
};
Value* get_value();
// ...
cout << get_value()->value() << endl;
Alternatively, you can maintain a map keyed on strings, the names of the values, and then look up the values with their names.
C++ addresses all variables via address so there is no way of just saying valueOf a variable (Languages which allow this e.g. python, perl have a runtime keeping this information)
You can implement something allowing use of a name to find a value by storing the values and their names in a std::map.
Well if you really want to do something like this, you might try using std::map (map< string, int* > ). Hovewer this would restrict you to one variable type, unless you delve into some ugly pointer magic. Either way it will be ugly and trust me you really don't want to go down this path. Why do you even need such feature? If for debugging purposes, use a debugger.
As said already, C++ provides no reflection. But you can use some key/value mapping on your own.
When only one value type (e.g. int) is required, you can use an STL associative container (map) out of the box.
If you need to support multiple value types, i recommend a look into boosts Variant library.
This would need something akin to reflection or eval which C++ doesn't have.
No, C++ does not provide that facility. You may be able to hack something together with macros (or other trickery) but it's likely to be fairly ugly.
Since I can think of no good reason of the top of my head why this would be useful, perhaps you could enlighten us. When something cannot be done in a certain way, it's often good to step back to the base requirements and see if there's another way.

how to call functions from header file [duplicate]

This question already has answers here:
What is this weird colon-member (" : ") syntax in the constructor?
(14 answers)
Closed 5 years ago.
CWmcaIntf::CWmcaIntf() :
m_hDll(NULL),
m_pLoad(NULL), m_pFree(NULL), m_pSetServer(NULL), m_pSetPort(NULL), m_pIsConnected(NULL),
m_pConnect(NULL), m_pDisconnect(NULL), m_pTransact(NULL), m_pQuery(NULL), m_pRequest(NULL), m_pAttach(NULL),
m_pDetach(NULL), m_pDetachWindow(NULL), m_pDetachAll(NULL), m_pSetOption(NULL),
m_pSetAccountIndexPwd(NULL), m_pSetOrderPwd(NULL), m_pSetHashPwd(NULL), m_pSetAccountNoPwd(NULL), m_pSetAccountNoByIndex(NULL)
i dont know what this grammer means. i am trying to use a header file 'CWamInf'. and want to know different methods or problems .. thanks..
I don't know how much you know about headers classes and stuff so I'll try to explain everything I can.
CWmcaIntf::CWmcaIntf() :
The CWmcaIntf:: means that the function that is about to be defined after the double colon is within the class "CWmcaIntf".
The CWmcaIntf() is a constructor : it has the same name as the class and its purpose is to construct each object of a class depending on the code you put in it. I'd say that often, its only purpose is to initialize member variables. If it isn't clear yet, check this link.
m_hDLL(NULL)
As you most certainly know, programmers tend to respect and harmonize on coding conventions. One of those is to name all member variables by m_something, so your code become easier to understand for you and everyone else.
So here, all you got is a constructor initializing a lot of member variables to NULL, which means that when a CWmcaIntf object will be constructed, its member variables will be equal to nothing and only be modifiable with setters if data are properly encapsulated.
Now if the purpose of your question was for us to tell you more about what does mean the member variables, and what the constructor may do, well don't expect an answer since zero details ae given and nothing even matches the tutorial explaining how to properly ask a question.

How to get a list of a class's member variables in C++? [duplicate]

This question already has answers here:
How can I add reflection to a C++ application?
(28 answers)
Closed 7 years ago.
Is there a way that I could obtain a list or maybe iterate through a list of each member variable of a class -regardless of it's type.
My intention is to add them all to a template std::map.
class Person
{
int Age;
char *Name;
template<typename Container> std::map<char *, Container> List;
void MakeList()
{
for(auto i : Person.memberVariables)
{
List.emplace(i);
}
}
};
Could I do something like the above to add each variable of my class to the list, regardless of how incorrect the other code is. The adding to the list is what I'm interested in.
Thanks in advance.
No, you can't do it in C++. this is called reflection which is currently not supported in C++.
The ISO C++ comitee talks about compile time reflection that is proposed for C++17 that will let you to iterate over class members on compile time. but it will take much time until this feature will be standarized and be implemented on the common compilers
as a side note, I don't see why one would want to iterate over member variables other then maybe implementing serialization method , which in this case I would require the class to implement serialize method and enforce it with SFINAE.
If there is, I would be very surprised.
This is called reflection, and as far as I know this isn't supported by C++.

C++, unmanaged, class, members: How (if at all) can I list all the members in a class? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Iterate through struct variables.
So I have a header file and a code file. The class is representation of a View that will be queried from stored proc. For each col. in view there is one data member in class.
Currently in code we have something like this:
Load( Reader reader)
{
m_col1 = reader("m_col1");
m_col2 = reader("m_col2");
..
}
How can I write a code that will iterate through member variables and give me code like:
Load( Reader reader)
{
For (each str in ArrayOfMemberVariables)
variableLValue(str) = reader(str); // str = m_col1, m_col2 ...
}
The C++ reflection question has been brought up several times. Unfortunately, it's not possible unless you manage the metadata yourself. See this question for more details.
If you mean declaring variables names dynamicly like in PHP for example (using other variable names), you can't do that in C++.
In C++ you don't have the notion of reflection like in Java where you can introspect the variables of your class and code around that to do things like serialization with knowing in advance the class members.