Predefined instances of C++ class enum vs static - c++

I have a class that is a bit complex to initialize. It is basically a tree structure and to create an instance the current constructor takes the root node. Nevertheless there are some instances that will be used more often than others. I would like to make it easier for the user to instantiate this ones faster and easier. I was debating what the best option would be.
First option: using enum to choose between different options in the constructor.
enum CommonPatterns {TRIANGLE, DIAMOND};
typedef struct PatternNode {
int id;
vector<PatternNode*> child;
} PatternNode;
class Pattern {
private:
PatternNode root;
public:
//Constructor that takes the root of the tree
Pattern (PatternNode root) { this->root = root; }
//Constructor that takes enum to create some common instances
Pattern (CommonPatterns pattern)
{
PatternNode predefined_root;
if (pattern == CommonPatterns::TRIANGLE)
{
//Build tree structure for the triangle
}
else if (pattern == CommonPatterns::DIAMOND)
{
//Build tree structure for the diamond
}
Pattern(predefined_root);
}
}
Second option: predifining some static instances
Pattern.h
enum CommonPatterns {TRIANGLE, DIAMOND};
typedef struct PatternNode {
int id;
vector<PatternNode*> child;
} PatternNode;
class Pattern {
private:
PatternNode root;
static Pattern createTriangle();
static Pattern createDiamond();
public:
//Constructor that takes the root of the tree
Pattern (PatternNode root) { this->root = root; }
//Predefined common instances of patterns
const static Pattern TRIANGLE;
const static Pattern DIAMOND;
}
Pattern.cc
Pattern::Pattern createTriangle()
{
PatternNode root;
//Create the tree for the triangle
return Pattern(root);
}
Pattern::Pattern createDiamond()
{
PatternNode root;
//Create the tree for the diamond
return Pattern(root);
}
Pattern Pattern::TRIANGLE = Pattern::createTriangle();
Pattern Pattern::DIAMOND = Pattern::createDiamond();
I don't understand that well the implications of using static performance wise so I would appreciate some suggestions.

As usual when people ask for the performance benefits, the first rule of optimization of code applies: If you think, you have a performance problem, measure the performance.
So my (and many a a people's) opinion is, that you should treat this problem with other things in mind, e.g. what is more clear to the user and/or the reader of the code (which is often yourself, so be extra nice to them!) or what code structure makes it easier to test.
Unfortunately those are a bit up to opinion, so now I will share mine:
Having separate functions for these seems cleaner to me.
It means that for testing purposes you have more but smaller tests, which makes it easier to spot the exact problem, when a test fails.
Related: The constructor is smaller and hence less error prone.
For the user it is extremely specific: He gets a function in the class namespace whose name says what it does.
If you go that route, remember to document these static functions in a way that a user will stumble upon them, e.g. mention them in the class documentation and/or the constructor documentation.
Although the same holds for documentation of the enum.
Lastly let me hazard a guess regarding performance:
Although I don't expect any noticable performance issues either way, the static function version has the advantage that the compiler may optimize it more easily as it (seems to) depends only on compile-time data.
Again to really find out about performance, you would have to
measure the performance differences or --even better--
disassemble the code and see what the compiler actually did with your code.

Related

Can I group attributes of one class into one map?

If I have class "node", and wish to include all possible (say int) attributes. Is grouping them into one map good solution.
So instead:
class node{
int color;
int isVisited;
int weight;
public:
};
To have
class node{
map<string, int> property;
public:
setProperty(string property_label, int property_value)
{property[propery_label] = property_value;};
};
int main(){
node n;
n.setProperty("color",int(color::red));
n.setProperty("isVisited", 1);
n.setProperty("weight", 12);
}
EDIT:
The reason to do this is that, when transforming a graph, some local properties (like is visited during some traversal, or is it marked) are needed somewhere in the middle of an algorithm, but these local properties do not represent intrinsic property of a node, and are not needed in the output. Also, sometimes I need more than one "isVisited" variables.
One more reason is to keep the class "node" universal and open for new attributes that eventually might be needed.
The example you gave gives the impression that any node would have all the properties you provided (colour, isVisited, weight). If so it is (usually) better to keep the original class you started with.
There might be a few scenarios in which a map (or possibly rather std::unordered_map) might be superior, though; just a few examples:
You have a large number of possible (but pre-defined) attributes and each node only needs a rather small subset of. Possibly an enum is better suited as key then.
You want/need to store arbitrary attributes unknown at compile time.
Each node has the same attributes, but you mainly access them via user input; then especially an unordered_map could be faster than a (possibly long) if-else-chain.
In the end, all depends on the use case...
For strings as keys possibly a trie might be an interesting alternative, too.
A class (identical to a struct except it defaults to private access rather than public) is primarily to group elements of data and/or functionality together.
You node seems to simply group together three elements. So you probably want to start off with something as simple as:
struct node // access is public by default
{
int color;
int isVisited; // maybe a bool rather than int?
int weight;
}
...
node myNode;
myNode.color = ...
...
std::cout << myNode.weight;

Inter-Module Functionality List in C++ - is it a bad idea?

In an old game of mine, I reached a point where keeping a header containing all possible code pieces for player "weapons", for lack of better word, forced recompilation of good 30% of the program. (If you are not into games, think about code for brushes and tools in a graphics editor, or buttons on calculator.) Then I decided that I'm not into keeping a list of what program can do, and came up with something more automatic... but it abuses global constructors.
Specifically, I made a class of double-linked list nodes that registered themselves into public class-static scope list of these nodes. Then, whenever I added a functionality of "known kind" into the program, I inserted a file-static scope list node exposing an object describing that functionality to the parts of the program which actually used it (usually a name, some virtual functions, and in some cases private variables). This means that if I want to add a new functionality of that kind to the program, I don't need to recompile any other module; the same if I want to remove it.
When I described this to my colleagues, most found this concept suspect, but I didn't receive any constructive feedback beyond some people suggesting using a non-language mechanism, like an external preprocessor. So... is it a bad practice to use setups like that, assuming you document them? Should I use it in my future programs? Maybe there's a way to explicitly ask linker to generate something like this?
Here's the header code for completeness, though I think you can answer my questions without looking at it. One could add destructor for safety, I guess... and the example usage is trivial of course.
#include <iostream>
using namespace std;
//general header
template <class Content>
struct InterFileListNode {
InterFileListNode * next, * prev;
Content content;
static InterFileListNode * first, * last;
InterFileListNode(const Content & t) : content(t) {
if (last==0) {
first = last = this;
next = prev = 0;
} else {
prev = last;
next = 0;
last->next = this;
last = this;
}
}
};
template <class Content>
InterFileListNode<Content> * InterFileListNode<Content>::first = 0;
template <class Content>
InterFileListNode<Content> * InterFileListNode<Content>::last = 0;
//header for functionality type
struct Functionality {
const char * name;
void (*funcptr)(void);
};
typedef InterFileListNode<Functionality *> FunctionalityNode;
//module with functionality
void nothing() {}
static Functionality foobar = {"do nothing", nothing};
static FunctionalityNode node(&foobar);
//module using functionality (usually a toolbox, but here for simplicity not):
int main() {
FunctionalityNode * ptr = FunctionalityNode::first;
while (ptr != 0) {
cout << ptr->content->name << endl;
(ptr->content->funcptr)();
ptr = ptr->next;
}
}

Pattern for storing multiple types of struct in a C++ std::<vector> container

I have a data structure which represents a train, which can be made up of many types of car, for example the train engines, a grain car, a passenger car, and so on:
struct TrainCar {
// ...
Color color;
std::string registration_number;
unsigned long destination_id;
}
struct PowerCar : TrainCar {
// ...
const RealPowerCar &engine;
}
struct CargoCar : TrainCar {
// ...
const RealCargoCar &cargo;
bool full;
}
std::vector<TrainCar*> cars;
cars.push_back(new TrainCar(...));
cars.push_back(new TrainCar(...));
cars.push_back(new CargoCar(...));
cars.push_back(new CargoCar(...));
cars.push_back(new CargoCar(...));
An algorithm will iterate through the cars in the train, and decide how to route/shunt each car (whether to keep it in the train, move it to another point in the train, remove it from the train). This code looks like:
std::vector<TrainCar*>::iterator it = cars.begin();
for (; it != cars.end(); ++it) {
PowerCar *pc = dynamic_cast<PowerCar*>(*it);
CargoCar *cc = dynamic_cast<CargoCar*>(*it);
if (pc) {
// Apply some PowerCar routing specific logic here
if (start_of_train) {
// Add to some other data structure
}
else if (end_of_train && previous_car_is_also_a_powercar) {
// Add to some other data structure, remove from another one, check if something else...
}
else {
// ...
}
}
else if (cc) {
// Apply some CargoCar routing specific logic here
// Many business logic cases here
}
}
I am unsure whether this pattern (with the dynamic_casts, and chain of if statements) is the best way to process the list of simple structs of varying types. The use of dynamic_cast seems incorrect.
One option would be to move the routing logic to the structs (so like (*it)->route(is_start_of_car, &some_other_data_structure...)), however I'd like to keep the routing logic together if possible.
Is there a better way of iterating through different types of simple struct (with no methods)?, or do I keep the dynamic_cast approach?
The standard solution to this is called double-dispatch. Basically, you first wrap your algorithms in separate functions that are overloaded for each type of car:
void routeCar(PowerCar *);
void routeCar(CargoCar *);
Then, you add a route method to car that is pure virtual in the base-class, and implemented in each of the subclasses:
struct TrainCar {
// ...
Color color;
std::string registration_number;
unsigned long destination_id;
virtual void route() = 0;
}
struct PowerCar : TrainCar {
// ...
const RealPowerCar &engine;
virtual void route() {
routeCar(this);
}
}
struct CargoCar : TrainCar {
// ...
const RealCargoCar &cargo;
bool full;
virtual void route() {
routeCar(this);
}
}
Your loop then looks like this:
std::vector<TrainCar*>::iterator it = cars.begin();
for (; it != cars.end(); ++it) {
(*it)->route();
}
If you want to choose between different routing-algorithms at run-time, you can wrap the routeCar-functions in an abstract base class and provide different implementations for that. You would then pass the appropriate instance of that class to TrainCar::route.
If the number of classes is manageable, you can give a try to boost::variant.
Using "sum types" in C++ is sometimes a mess, so it is either this or double dispatching.
The classical OO solution would be to make all of the relevant functions
virtual in the base class TrainCar, and put the concrete logic in each
class. You say, however, that you'd like to keep the routing logic
together if possible. There are cases where this is justified, and the
classical solution in such cases is a variant union (boost::variant,
for example). It's up to you to decide which is better in your case.
Compromises are possible as well. For example, one can easily imagine a
case where the routing logic is somewhat independent of the car type
(and you don't want to duplicate it in each car type), but it does
depend on a certain number of characteristics of the car type. In this
case, the virtual function in TrainCar could simply return an object
with the necessary dependent information, to be used by the routing
algorithm. This solution has the advantage of reducing the coupling
between the routing and TrainCar to the minimum necessary.
Depending on the nature of this information, and how it is
used, the returned object could be polymorphic, with it's inheritance
hierarchy reflecting that of TrainCar; in this case, it must be
allocated dynamically, and managed: std::auto_ptr was designed with
exactly this idiom in mind.

Design pattern for large decision tree based AI in c++

I'm currently writing an AI for a game that is written in c++. The AI is conceptually fairly simple, it just runs through a decision tree and picks appropriate actions. I was previously using prolog for the decision engine but due to the other developers using c++ and some issues with integrating the prolog code I'm now trying to port it to c++.
Currently I have a bunch of facts and rules in prolog (100+). Many express things in the form, if game_state then do action xyz. Most of the rules are fairly simple with a few being rather complex. I looked at a finite state machine approach, but that didn't seem to scale to the larger situations so well.
My first attempt at coding this up in c++ was a huge nightmare of if then else case statements. I had this sort of code popping up everywhere:
if( this->current_game_state->some_condition == true ){
if( this->current_game_state->some_other_condition == false ){
//some code
}else{
return do_default_action();
}
}else if( this->current_game->another_condition ){
//more code
}
The complexity became quickly unmanageable.
If there a good way to code this sort of problem in c++? Are there any good design patterns to deal with this type of situation? There is no requirement that the logic has to be contained within the source, it just needs to be accessible from c++. The only real requirement is that it is reasonably fast.
I also looked at rules engines and if fast enough they could be appropriate. Do you know if there is a open source c++ rules engine that would be appropriate?
Code is Data, and Data is Code. You've got working code - you just need to expose it to C++ in a way it can compile, then you can implement a minimal interpreter to evaluate it.
One possibility is to take your Prolog rules and translate them in the most direct way possible to a data structure. Maybe you could design a simple table like:
struct {
State coming_from;
Event event;
void (*func)(some, args);
State going_to;
} rules[] = {
{ WANDERING_AROUND, HEAR_SOUND, look_around, ENEMY_SEEN },
{ ENEMY_SEEN, GUN_LOADED, fire_gun, SNEEK_AWAY },
{ next, rule, goes, here },
etc...
}
Similarly, function calls can populate data structures in such a way that it looks similar to your original Prolog:
void init_rules () {
rule("Parent", "Bill", "John");
rule("Parent", "Paul", "Bill");
// 99 more rules go here...
}
Then you implement a simple interpreter to traverse that data structure and find the answers you need. With less than 1000 rules, a brute force approach at searching is likely to be fast enough, but you can always get clever later and try to do things the way a real Prolog environment would when the time comes.
You can use polymorphism. Calling a virtual function is effectively a big-ass switch/case that's done and optimized for you by the compiler.
class GameState {
virtual void do_something() { std::cout << "GameState!"; }
// some functions
virtual ~GameState() {}
};
class SomeOtherState : public GameState {
// some other functions
virtual void do_something() { std::cout << "SomeOtherState!"; }
};
class MyFinalState : public GameState {
virtual void do_something() { std::cout << "MyOtherState!"; }
};
class StateMachine {
std::auto_ptr<GameState> curr_state;
public:
StateMachine()
: curr_state(NULL) {}
void DoSomething() { curr_state->DoSomething(); }
void SetState(GameState* ptr) { curr_state = ptr; }
template<typename T> void SetState() { curr_state = new T; }
};
int main() {
StateMachine sm;
sm.SetState(new SomeOtherState());
sm.SetState<SomeOtherState>();
sm.DoSomething(); // prints "SomeOtherState!"
sm.SetState<MyFinalState>();
sm.DoSomething(); // prints "MyFinalState!"
}
In the above example, I didn't need to switch about any of the states, or even know that different states exist or what they do (in the StateMachine class, anyways), the selection logic was done by the compiler.
If you want to convert your prolog code to c++ code,
have a look at the Castor library (C++) which enable Logic Programming in C++:
http://www.mpprogramming.com/Cpp/Default.aspx
I haven't tried it out myself, so I don't know anything about it's performance.
If you want to use a state-machine, have a look at Boost.Meta State Machine
I don't really get why a finite state machine is not sufficiant for your game. It is a common way to do what you want to. You could make it data driven to stay you code clean from concrete actions. The finite state m. is also described in "AI for Game Dev" O'Reilly (David M. Bourg & Glenn Seemann)
You maybe want to split you rules in several smaller rule sets to keep the machine small and understandable.
How about use mercury? its basically built to interface with C code.
Trying to match Prolog's expressive power with state machines is like trying to outrun a car with a bicycle.
Castor is probably the way to go. It is very lightweight and allows smooth interop between Logic programming and rest of C++. Take a look at the tutorial videos on http://www.mpprogramming.com/cpp

Is Polymorphism worth an increase in coupling?

I'm writing a simplistic game to learn get some more C++ experience, and I have an idea where I feel polymorphism almost works, but doesn't. In this game, the Party moves fairly linearly through a Map, but can occasionally encounter a Fork in the road. A fork is (basically) an std::vector<location*>.Originally I was going to code something like the following into the a Party member function:
if(!CurrLocation->fork_.empty())
// Loop through forks and show options to the player, go where s/he wants
else
(CurrLocation++)
But I was wondering if some variant of the following might be better:
CurrLocation = CurrLocation->getNext();
With Fork actually being derived from Location, and overloading some new function getNext(). But in the latter case, the location (a low level structure) would have to be the one to present the message to the user instead of "passing this back up", which I don't feel is elegant as it couples location to UserInterface::*.
Your opinions?
All problems can be solved by adding a level of indirection. I would use your suggested variant, and decouple Location from Party by allowing getNext to accept an object that resolves directional choices. Here is an example (untested):
class Location;
class IDirectionChooser
{
public:
virtual bool ShouldIGoThisWay(Location & way) = 0;
};
class Location
{
public:
virtual Location * GetNext(IDirectionChooser & chooser)
{
return nextLocation;
}
virtual Describe();
private:
Location * nextLocation;
};
class Fork : public Location
{
public:
virtual Location * GetNext(IDirectionChooser & chooser)
{
for (int i = 0; i < locations.size(); i++)
if (chooser.ShouldIGoThisWay(*locations[i]))
return locations[i];
}
virtual Describe();
private:
vector<Location *> locations;
};
class Party : public IDirectionChooser
{
public:
void Move()
{
currentLocation = currentLocation->GetNext(GetDirectionChooser());
}
virtual IDirectionChooser & GetDirectionChooser() { return *this; }
virtual bool ShouldIGoThisWay(Location & way)
{
way.Describe();
cout << "Do you want to go that way? y/n" << endl;
char ans;
cin >> ans;
return ans == 'y';
}
};
You should use polymorphism as long as it makes sense and simplifies your design. You shouldn't use it just because it exists and has a fancy name. If it does make your design simpler, then it's worth the coupling.
Correctness and simplicity should be the ultimate goal of every design decision.
I think you spotted the issues yourself and can probably work it out with your knowledge of the rest of the system or a few more details here for us to look at.
As has been mentioned:
Polymorphism should be used to simplify the design - which it would do in this case, so well spotted.
You have an issue with the coupling - again well spotted, coupling can lead to problems later on. However, what this says to me is that the way in which you are
applying the polymorphism might not be the best way.
Programming to interfaces should allow you to hide the internal details of how the system is put together and so reduce the coupling.
Polymorphism does not lend to greater coupling, I think they are separate issues.
In fact if you are programming to interfaces and following general inversion of control patterns then you will lead to less or zero coupling.
In you example, I don't see how location is coupled to UserInterface?
If this is the case, can the coupling be removed through another level of abstraction in between UserInterface and Location, such as LocationViewAdapter?