C++ "valueof" function?

Status
Not open for further replies.

Kenn37

Ars Scholae Palatinae
1,049
Allow me to post some sample code:
Code:
class myClass
{
  public:
    bool class1;
    bool class2;
};

void main()
{
  string myString = "class1"
  myClass exampleClass;

Ok, I'll just pause there for a second. Now, what I want, is to do something like "exampleClass.(valueof myString) = 1". myString contains the name of the class' variable exactly, and I'm wondering if there's a way to substitue it in.

Also, I know someone will suggest using "if (myString = "class1") exampleClass.class1 = 1". But this is NOT what I'm looking for.
 

Karpage

Ars Scholae Palatinae
725
Subscriptor
Also, I know someone will suggest using "if (myString = "class1") exampleClass.class1 = 1". But this is NOT what I'm looking for.

That approach works well, and I'm pretty sure its the only way. What specifically is wrong with it?

Code:
class myClass
{
private:
 map<const char*, bool *, ltstr> members;
public:
 bool &getMember( string str)
  { return *members[str] }
myClass();

bool class1;
bool class2;

};

int main()
{
string myString = "class1"
myClass exampleClass;
exampleClass.getMember(myString) = true;
}


myClass::myClass()
{
  members["class1"] = &class1;
  members["class2"] = &class2;
}

Haven't compiled it, and there may be a better way using references or setting up the table statically, but it should work.

BTW, main should be type int.
 

Karpage

Ars Scholae Palatinae
725
Subscriptor
Compiles verbatim under g++ 3.0.4.

Code:
#include <iostream>
#include <map>
#include <cstring>
#include <string>

struct ltstr
{
	bool operator()(const char* s1, const char* s2) const
  		{ return std::strcmp(s1, s2) < 0; }
};

class myClass
{
private:
	std::map<const char*, bool *, ltstr> members;
public:
	bool &getMember( std::string str )
		{ return *members[str.c_str()]; }
	myClass();

	bool class1;
	bool class2;
};

myClass::myClass()
: class1(false), class2(false)
{
	members["class1"] = &class1;
	members["class2"] = &class2;
}

int main()
{
	std::string myString( "class1" );
	myClass exampleClass;

	std::cout << exampleClass.getMember(myString) << std::endl;
	
	exampleClass.getMember(myString) = true;
	
	std::cout << exampleClass.getMember(myString) << std::endl;
}
 

angst

Smack-Fu Master, in training
51
Code:
class myClass{ 
public:    
 bool class1;
 bool class2;    
 bool& ref;
};

you can't have a referencing member without a constructor initializer for that member ...

Code:
class myClass{ 
public:
 myClass(bool b) : ref(b) {}
.
.

-------

Code:
class myClass{private:
 map<const char*, bool *, ltstr> members;
public:
.

you should never, ever use pointers as the keys to any lookup tables, unless it is your intent in a first place, like keeping track of valloced regions in memory debuggers, where the value of the pointer is unique to s specific memory address ( at least in most architectures ) or maybe when you can guarantee that the key lookups will always occur from a predetermined key table. Nevetherless, in this case you should consider using string objects as your map keys.
 

Karpage

Ars Scholae Palatinae
725
Subscriptor
you should never, ever use pointers as the keys to any lookup tables, unless it is your intent in a first place, like keeping track of valloced regions in memory debuggers, where the value of the pointer is unique to s specific memory address ( at least in most architectures ) or maybe when you can guarantee that the key lookups will always occur from a predetermined key table. Nevetherless, in this case you should consider using string objects as your map keys.

STL documentation

Their example should look familiar... no offense, but I trust them more than I trust you.
 

EgalitarianBovine

Ars Tribunus Angusticlavius
8,086
Kenn37:

doing something like that is not really feasible in a language as low-level as C++. C++ does not store a whole lot of metainformation about a class, and it certainly does not store string indexes to offsets for fields in instances. So unless you go about doing it manually, you'll have to do it manually using "if/elseif/elseif/.../else" constructs.

This is possible in other languages like Java, and python, since they store the appropriate metainformation about classes.

As a side note, you should not need to do this. What do you need to do that requires this kind of functionality? Most of the time, it is possible to rework the design so that it provides the same functionality, without requiring this hack.

Even in languages where operations like this are allowed (like, python, were it's as simple as: x = "class1"; obj.__dict__[x] = 3), heavy use of this feature is frowned upon and seen as an indicator of bad design.

-EB
 

angst

Smack-Fu Master, in training
51
Their example should look familiar... no offense, but I trust them more than I trust you.

no offense, but I don't think you understand the example. consider the following snippets ...

Code:
const char* key_1 = "abc";
const char* key_2 = "abc";
string key_3 = "abc";

map<const char*, bool> m;
m["abc"] = true;

now let's try to find our entry

Code:
m.find(key_1) != m.end( ); // true, pointer to const string "abc" is used as a key and as expected the entry is found
m.find(key_1) != m.end( ); // also true, since "abc" is a string literal key_2 is really a pointer to the same address as literal "abc" and key_1
m.find(key_3.c_str( )) != m.end( ); // FALSE, std string does a copy on assignment, so internally the string value is copied to a new location and c_str( ) call produces a fresh pointer as the key, which obviously is quite different from key_1 and key_2 pointers

as you can clearly, see the example posted on the sgi's site uses ONLY string literals, so pending compiler implementation they can pretty much guarantee that for that example each reference to that literal will produce the same pointer, thus producing the same lookup key ( that's what i ment by predetermined lookup tables ). In reality they could use generic pointers with casts and get the same effect.

Code:
 map<const char*, int, ltstr> months; 
 months["january"] = 31;
 months.find("january"); // success

could be substituted by

Code:
 map<void*, int, ltstr> months; 
 months[(void*)"january"] = 31;
 months.find((void*)"january"); // success

however as soon as you would do anything resembling this ( ignore the memory leak )

Code:
 map<const char*, int, ltstr> months; 
 months["january"] = 31;
 months.find(strdup("january"); // failure

the lookup would fail, event though the values are the same STL, still uses the pointer values as the keys. I hope this rather convoluted post made things clearer
 

Karpage

Ars Scholae Palatinae
725
Subscriptor
map<const char*, bool> m;
Thats not what my map was.

std::map<const char*, bool *, ltstr>
Note that the comparison function is overridden.

m.find(key_3.c_str( )) != m.end( ); // FALSE, std string does a copy on assignment, so internally the string value is copied to a new location and c_str( ) call produces a fresh pointer as the key, which obviously is quite different from key_1 and key_2 pointers
Irrelevent. The pointers are never compared. Instead, the map uses the ltstr function object, which compares the strings pointed to.

My example code runs correctly, which would not happen if pointers were being compared. When I compile your code using ltstr too, your first three tests all return true, indicating that the strings are being compared, not the pointers.

[This message was edited by Karpage on April 20, 2002 at 22:09.]
 
Status
Not open for further replies.