A C++ program with user-defined variables - c++

I'm writing a code that implements simple command line calculator, and I wanted to add a function for user to create his own variables with numeric values for better calculations. Can anyone share any advice, what technique should I use? I thought about creating an allocated two-dimensional string array and later just converting numeric values or use a template, something like that:
template<class T>
void UserVariables(T varname, T varvalue){
T tArray[2][MAX_VARS]={ {varname1, varvalue1}, {varname2, varvalue2}, ... };
....
}
Maybe there are any better and less noobie-ish decisions out there? Thanks in advance.

Your options are here:
std::unordered_map
std::map
std::unordered_multimap
std::multimap

I don't see how your attempt would work - templates are evaluated at compile time, not run time, so the user can't make new variables one the code is running.

Related

How can I transform a pointer to the type I input in C++?

I have a question here:
I want to generate a type_t pointer (type_t *), pointing to a memory block, with specified value stored in it.
In another word, its input is:
string value,
string type
and its output is:
(type*)pointer , pointing to some memory storing 'value'.
I don't know how to do this. I tried to use templates, but I think it need 'type', not the "string type". My only idea is to generate a new cpp file with these information and use it to achieve that. But that's quite awkward when I want to generate enoumous values...
I come up to this question when diving in clang tooling, with QualType and binary value in my hand, and I want to recover the original value. I tried to use the constructors in Expr or VarDecl, but failed to achieve my goal.
Can anyone provide some thoughts? Thanks a lot for your reading this message.
Thanks a lot for all your efforts! I think I should get the question clearer with some code
My goal is to write a function like this
type_t* func(QualType type_t, string value)
{ /* some magic here */}
or maybe
type_t* func(string type_t, string value)
{ /* some magic here */}
It sounds impossible, cause the type is not even determined before the input QualType is determined.
Sure void* is a great idea to be used as a middleware, I still wonder how I could write
type_t* func(string type_t, void* memory_block)
{ /* some magic here */}
I think the question is the same as: How can we input a type message and output some value (already existed maybe) with that type?
Thanks again.
This kind of functionality is not provided in c or c++.You can do that in python using exec().
One thing you can do to solve this problem is to declare some of the variables beforehand with the same name as the string that you want to pass.
You can use void pointers to cast any type of pointers. let me know if it works.IT would be great if you provide a script of what you want to do

Can I access a struct passed into a template generically?

As per the title, this is what I am looking to do. Basically I am looking to load in structures from files, but support every kind of structure, so I am attempting to do it in a template. This is my first time using templates really so excuse my ignorance!
I want to be able to do something like:
template<class T> T ConfigLoader::LoadStructFromFile(T a)
{
int noOfThingsInStruct;
noOfThingsInStruct = a[1];
return a;
}
Is this at all possible?
My function does sorting of the string loaded in from files etc but thought I would leave that part out.
I want to be able to get this value to use it to loop and give the struct the correct number of values it is looking for.
So you want to dynamically figure out what members and methods are in a struct? Similar to, say, what you can do in Javascript in runtime, but in compile time? No, you can't. However, you can make a template policy and base this function on that.
Simple answer: impossible.
Long answer: still no.
Detour:
you can use something based on type traits. Create a template class numberOfElements<typename T> and overload it for every struct you need with a value you expect. Then, use it in your LoadStructFromFile, since you know T.
You can also use SFINAE to test for some function that'll return the number of elements in a struct. If a given class/struct implements it, just use it to get the number of members. If not - assume there's only 1 member (or whatever you wish).

Is it recommended to specify e.g. vector<t> in my public interface?

I'm new to C++, and while writing a class I realized one of my methods was asking for a vector-of-vectors. Should this be done or should I rethink my class's interface? (How?)
I think it is no problem what container you use. You could do it like
void func(std::vector<std::vector<int> > const& int_matrix);
or in C++11, successive > won't be considered as '>>' so you could also use
void func(std::vector<std::vector<int>> const& int_matrix);
But the problem is, if your work are published as binary instead of source code, the users of the interface should have the same STL implement as yours, otherwise strange runtime errors may occur. So use STL container as interface is not proper in this situation. You have to define some structures yourself as the type of parameters.
A vector of vectors isn't necessarily a bad thing. If you need something like a multidimensional array, then you need what you need. (Just make sure you pass the vector by [const] reference).
You might want to change the title of your question though, because the title says "vector<T>" (boldness because it thinks it's an HTML tag) but your question asks about a vector of vectors.
IMO, if possible it's better to merge all the vectors into a single vector. Having vector of vector doesn't make much sense to me.

How to generate C++ Dynamic Objects names?

I'd like to generate a number of objects (in C++) based on the amount/number the user enters.
Now I've somewhere heard that it has to be done using pointer tricks, creating a pointer to an array of the Object type required, and then dynamically increasing the size of array ( at runtime ).
Isn't there a workaround of directly using names like
Object1, Object2..... ObjectX
instead of having
Classname *Object[]
and then using the array index to get the object ?
In either case, it'd be great if someone could clarify on the issue.
Thanks !
If you want dynamically-sized array, then use std::vector. You won't be able to resize a built-in array.
If you want to be able to get an object by string name, then you should use std::map, it has an indexer:
std::map<string, Classname> myMap;
myMap["Object1"] = Classname();
Classname newClassname = myMap["Object1"];
So far no-one has explained why your thinking is flawed. C++ is a compiled language, and it goes to great lengths to turn the source program into efficient machine code. For this reason, the names you give variables are available to the program only at compile time, when you turn it from source into an executable file. Afterwards, when you want to create objects dynamically, those kinds of information are no longer available. The program only knows about the machine addresses where operands to machine instructions are located.
No, there isn't. Moreover, you don't need to; use std::vector.
When I began programming 9 years ago I asked myself the same question. The answer is: you can't.
You can indeed use an array and resize it dynamically, however using an stl vector is much easier (once you learn how to use it).
You can not do that because C++ doesn't have an "environment" (reflection) where variables (and metadata) can reside. Moreover, in C++ all variable names are vanished when the code is compiled.
A way to achieve the effect you want is to use a Map where the keys are strings.

Best way to take a snapshot of an object to a file

What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that, right?
Contrived example:
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
int otherStuff;
};
Container myCollection;
I would like to be able to do something to see output along the lines of "myCollection: stuff = value, otherStuff = value".
But then if another member is added to Container,
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
string evenMoreStuff;
int otherStuff;
};
Container myCollection;
This time, the output of this snapshot would be "myCollection: stuff = value, evenMoreStuff=value, otherStuff = value"
Is there a macro that would help me accomplish this? Is this even possible? (Also, I can't modify the Container class.)
Another note: I'm most interested about a potential macros in VS, but other solutions are welcome too.
What you're looking for is "[reflection](http://en.wikipedia.org/wiki/Reflection_(computer_science)#C.2B.2B)".
I found two promising links with a Google search for "C++ reflection":
http://www.garret.ru/cppreflection/docs/reflect.html
http://seal-reflex.web.cern.ch/seal-reflex/index.html
Boost has a serialization library that can serialize into text files. You will, however, not be able to get around with now knowing what members the class contains. You would need reflection, which C++ does not have.
Take a look at this library .
What you need is object serialization or object marshalling. A recurrent thema in stackoverflow.
I'd highly recommend taking a look at Google's Protocol Buffers.
There's unfortunately no macro that can do this for you. What you're looking for is a reflective type library. These can vary from fairly simple to home-rolled monstrosities that have no place in a work environment.
There's no real simple way of doing this, and though you may be tempted to simply dump the memory at an address like so:
char *buffer = new char[sizeof(Container)];
memcpy(buffer, containerInstance, sizeof(Container));
I'd really suggest against it unless all you have are simple types.
If you want something really simple but not complete, I'd suggest writing your own
printOn(ostream &) member method.
XDR is one way to do this in a platform independent way.