Number of "constants" in enum [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
(How) can I count the items in an enum?
Is there a way to get the number of constants in enum?
For example:
enum C{id,value};
And later this would return 2:
//pseudo code
get<C>::value
And also, is it possible to access those constants via [] optor? Like i.e.:
C[0] would return id

Usually, you start at zero and the last member gives the size of the enum excluding it.
enum C { id = 0, value, size };
C::size is the size of the enum. Is it possible to access those constants via subscript? No, it is unfortunately most assuredly not possible. However, in this case, you don't really want an enum- you just want a constant array.

A common idiom used for this is
enum C {
id,
value,
LAST_ENUM_C // or something similar.
};
but that assumes no gaps in the enum values here (i.e. no id = 3, value = 15).

Related

How can I use a string as the name of an integer? C++ [duplicate]

This question already has answers here:
How to use a string as a variable name in C++? [duplicate]
(2 answers)
Closed 4 years ago.
Hello guys i´m new to programming and i ran into a problem. I have a String and I use the lenght of the String to create variables according to the lenght of the string. I want to use a string("usagetxt_whl_str") as the name of my integer. Every time the loop runs it should create a new variable with a diffrent name. for example: 1_var, 2_var and so on
QString usagetxt = "example"
int usagetxt_len = usagetxt.length();
int usagetxt_whl = 0;
QString usagetxt_whl_str = QString::number(usagetxt_whl);
while (usagetxt_whl != usagetxt_len){
usagetxt_whl = usagetxt_whl + 1;
**here im trying to create my var**int usagetxt_whl_str + "_var" = 0;* }
How can I get this to work?
Is it even possible?
C++ is a compiled language. So you cannot create a variable name at run-time.
However there are several alternatives that can address the need of having a dynamic number of "variables" (in reality of values). The first one is to use a vector. Here you create a vector that contains usagetxt_len integers :
std::vector<int> myvars(usagetxt_len);
You can then access each of these integers with the traditional indexing operator:
myvars[i] = i;
As indexing is numeric (starting with 0 of course), you can easily process them in loops.
Another approach to dynamic "variables" is based on strings. You can then define a name in a string, and access the variable:
std::map<string, int> myvalues;
You could then access specific values associated to strings:
myvalues["4_var"]=0;
myvalues["5_var"]=myvalues["4_var"]+3;
As you are new to programming, I think that the vectors will do the job. It's just a change in the way you think on a group of values.

Meaning of asterisk following a member function [duplicate]

This question already has answers here:
What is the function of an asterisk before a function name?
(4 answers)
Closed 6 years ago.
I am fairly new to C++ and I am trying to decode the piece of code shown below. In particular for the BaseSetAssoc::BlkType* line, I am not sure what the asterisk means in this case. I would appreciate some insight.
BaseSetAssoc::BlkType*
NMRU::accessBlock(Addr addr, bool is_secure, Cycles &lat, int master_id)
{
// Accesses are based on parent class, no need to do anything special
BlkType *blk = BaseSetAssoc::accessBlock(addr, is_secure, lat, master_id);
if (blk != NULL) {
// move this block to head of the MRU list
sets[blk->set].moveToHead(blk);
DPRINTF(CacheRepl, "set %x: moving blk %x (%s) to MRU\n",
blk->set, regenerateBlkAddr(blk->tag, blk->set),
is_secure ? "s" : "ns");
}
return blk;
}
BlkType isn't a member function, it's a type, possibly an enum or struct if not an inner class.
The BaseSetAssoc:: is needed to access such "inner" types (defined within a class, i.e. BaseSetAssoc).
So BaseSetAssoc::BlkType* is just a BaseSetAssoc::BlkType pointer.
It's not "following", it's "preceding". As the comments have said: it means that it is returning a pointer to BaseSetAssoc::BlkType, rather than a whole BaseSetAssoc::BlkType.
What does this mean? It means mostly that the pointer can be NULL, or non-existent. Before using the result of this function, it is almost mandatory that you check if it is NULL first.

Using a user variable to access a member of struct? C++ [duplicate]

This question already has answers here:
How to use a string as a variable name in C++? [duplicate]
(2 answers)
Closed 7 years ago.
Say I have the following struct:
struct movie {
char movie_name[32];
int rating;
int release_year;
char location;
}
Normally, I would access the rating by saying "movie.rating".
For this project, I have to take input from a text file. I will read a variable such as "movie_name" or "rating" or "release_year" from the file, and given that variable, I have to access the corresponding element of the struct.
Ex: if the input file reads "movie_name", then I want to access movie.movie_name. How do I do this without making 4 if statements? Is there another way?
if(input == "movie_name")
movie.movie_name = ...
else if(input == "rating")
movie.rating = ...
The real struct I'm working with has 20+ members, so I am trying to find a more efficient way to write this code.
Thanks in advance!
In C/C++ it is not possible to access variable using a string; so there is no way to do this using the struct you provide. A map might be an alternative:
map<string, int>
but then each variable will map on the same type of variable (int in this case)... You should look to the related questions: How to use a string as a variable name in C++? and Convert string to variable name or variable type
What you are looking for is called reflection. unfortunately, it is not supported in C++. One solution to your problem which is not an optimal one of course is to implement your struct as map of pair<key,value> as follow:
struct movie {
std::map<string,ValueType> foo;
}
However, the problem is the ValueType. If boost is available, Then this could be a better solution:
struct movie {
std::map<string,boost::variant<typeX, typeY>> foo;
}

Getting enum Values by its index [duplicate]

This question already has answers here:
Is there a simple way to convert C++ enum to string?
(35 answers)
How to convert an enum type variable to a string?
(35 answers)
Closed 8 years ago.
How can I access each value of the enum by the index?
for instance,
enum food{PIZZA, BURGER, HOTDOG};
as we all know, the index of the first element starts from 0 unless initialized.
How can I get the string value of the enum from the index?
How can I get it to print the PIZZA?
cout << food(0);
I know it's not correct, but please advise me thanks.
You can't get the string representation of an enum in c++.
You have to store them somewhere else.
Example
enum food{PIZZA, BURGER, HOTDOG}
char* FoodToString(food foodid)
{
char* foodStrings[3] = {"PIZZA","BURGER","HOTDOG"};
return foodstrings[foodid];
}
There's no way of doing that because there's no need to do that. Generally enums are used to replace integral values we use for example:-
int func ()
{
//...
if (something )
return 0;
return 1;
}
could be replaced with
enum Status { SUCCESS, FAILURE };
Status func ()
{
//...
if (something )
return SUCCESS;
return FAILURE;
}
for better readability.
If you want to get enum value by providing index then you can store index with enum values in some sort of map ( for unordered_map ).

Initialization List Problems [duplicate]

This question already has an answer here:
Initializing members with members
(1 answer)
Closed 8 years ago.
DoubleVector::DoubleVector(unsigned int buffer) : len(buffer), data(new base_int[len]), start(len / 2), end(start)
This produces a very large values for both start and end even though the buffer is set to 50. len contains the correct value of 50 but start and end both contain some value over a million. I then changed to code to the following.
DoubleVector::DoubleVector(unsigned int buffer) : len(buffer), data(new base_int[len]), start(buffer / 2), end(start)
Now both start and end were initialized with the correct values of 25. Why? Are you not supposed to assume there is any order in which the variables will be initialized?
The order of base member initialisation is the order that the member variables appear in the class definition.
It's best not to rely on that. (As to do so makes code very brittle).