I am creating a game that lets the player enter input, changes some states, then checks if a \"goal value\" is true (obviously this description is muchly simplified), and I
I'm thinking you can define your own class and work around using the 'assert' keyword, but I may have understood the question wrong.
http://www.cplusplus.com/reference/clibrary/cassert/assert/
There's no standard way to do it in C++. One solution is to write your own parser.
Another solution, that I'd recommend: embed a Lua interpreter in your program. Lua is a simple yet powerful programming language, that also has an extremely lightweight (<300kB) and easy-to-use interpreter. Read an introductory article here: http://www.ibm.com/developerworks/linux/library/l-embed-lua/index.html
Having Lua embedded in your game has a number of nice side advantages:
There is no standard way to compile expressions during runtime. You'll have to do it some other way.
You might consider using a scripting language, like Lua or Python, and embed it in your C++. That would allow your players the ability to program to the extent you want them to.
C++ doesn't have this as part of the language -- there is no way to, at runtime, get access to the same stuff that parsed your program.
I'm sure there are numerous third-party arithmetic parser libraries you could use, however.
Why not build your own expression classes?
class GoalBase
{
virtual bool goal() = 0;
};
class Enemies : public GoalBase
{
// ..
private:
int enemies_;
public:
Enemies(int start) : enemies_(start) {}
void kill() { if (enemies_) --enemies_; }
bool goal() { return enemies_ == 0; }
};
int main()
{
Enemies enemiesToKill(5);
enemiesToKill.kill();
// ..
if (enemiesToKill.goal()) {
// ..
}
return 0;
}
Other classes could have other methods, parameters, operators etc. Use your imagination.
Static expressions
(amendment to Macke's post)
When your expressions are known at compile time, you can use std::function
. However, the performance might not be optimal.
You can automatically register test at compile-time and execute them at run-time with (presumambly) minimal runtime overhead, using C++11 templates and macros. A proof-of-concept implementation can be found here.
In the long run, a language feature named "Contracts" could do the job. (N4415, N4435, N4378) Today, there are various libraries available to support contract programming.