Khaledvic
Khaledvic

Reputation: 516

who to make variables during run-time (in c++ )

I want to let the user of my program define variables , then makes mathematical operation on them like "define a:integer , b:double" then "print a*b"

I found that I can use "boost any" but I need the type of the variable be dynamically recognized because want to use variable(objects) of classes .... so I want to use the operation (+ * ...) defined in that class

It's like I want to make a container of different types but when I use items in this container later I use operation defined for this item type !

thanks in advance

Upvotes: 0

Views: 402

Answers (5)

Khaledvic
Khaledvic

Reputation: 516

The best way to do it is using Polymorphism in C++

Upvotes: 0

g19fanatic
g19fanatic

Reputation: 10941

If you must use c++, i'd suggest embedding a dynamic scripting language. Python, Lua and Javascript all come to mind.

You'd be able to do everything you want to do AND still compile the code to be an .exe.

Upvotes: 1

jszpilewski
jszpilewski

Reputation: 1632

I think you are expected to create and update some symbol table that is being updated when a define command is entered and consulted during an arithmetic operation. Generally you do not need to store a value of any type, you may assume a finite set of possible value types (integer, real etc.) and represent it in the table. Personally I would create a class with specific operation for every value type that is derived from the common base to which a reference would be stored in the symbol table.

Upvotes: 0

Vilx-
Vilx-

Reputation: 106930

That would not be possible, because when C++ compiles your code, it loses much of the information that is in your code, like function names and variable types. It knows them for the moment of compilation, and it produces machine codes that do what your code says, but in the end it's all discarded. (OK, not exactly true, but close to that).

So if you want to evaluate expressions that the user has entered, you'll need to do a lot of parsing in your own code. Perhaps another, dynamic language which has the "eval" statement would be more of use here?

Added: Suggested language: Javascript. Because you can work it in your browser on whatever platform you like.

Upvotes: 2

johnsyweb
johnsyweb

Reputation: 141820

From the comments:

Why C++? Why not a language that already offers dynamic typing and runtime evaluation? –

so what language do you suggest guys ?

Python.

Upvotes: 1

Related Questions