Is this proper use of dynamic_cast? - c++

I have three classes: Generic, CFG, and Evaluator.
Here's Generic:
class Generic: public virtual Evaluator, public CFG, public LCDInterface {
Here's CFG:
class CFG : public virtual Evaluator {
And Evaluator subclasses nothing.
I'm providing a DLL named PluginLCD, and it has a method called Connect:
void PluginLCD::Connect(Evaluator *visitor) {
visitor_ = dynamic_cast<Generic *>(visitor);
if(!visitor_)
return;
type_ = visitor_->GetType();
}
Here's how I'm compiling the DLL through scons:
env.SharedLibrary(['PluginLCD.cpp', 'Evaluator.cpp', 'Generic.cpp', 'CFG.cpp'])
Now, there are two scenarios in my code. One is in class LCDControl, which subclasses CFG. The other scenario is above where Generic subclasses Evaluator and CFG. Evaluator has a method called LoadPlugins, which does what its name suggests, passing this through to the DLL via method Connect. Well, in the first scenario the cast to Generic * in Connect should return NULL. However, in the second scenario, as far as I know, a valid pointer should be returned. It doesn't seem to be happening this way. Am I wrong about this?

dynamic_cast is known to break across module boundaries with many compilers (including MSVC and gcc). I don't know exactly why that is, but googling for it yields many hits. I'd recommend trying to get rid of the dynamic_cast in the first place instead of trying to find out why it returns null in your second scenario.

Related

Template based get component method fails on inheritance

Edit: The problem described below is incorrect, the code is in fact functional. However I'd still like to improve on the getComponent method, as dynamic_cast is certainly pretty slow.
Thanks
In the game engine I have developed I have a Component based system similar to Unity's. The GetComponent method is as follows:
template <typename CompType>
inline CompType getComponent()
{
for(Component * currComp : components)
{
CompType currentEntry = dynamic_cast<CompType>(currComp);
if (currentEntry != nullptr)
{
return currentEntry;
}
}
return nullptr;
}
I have a problem however.
class SomeComponent : public Component
{//Some class};
class SomeSpecialComponent: public SomeComponent
{//Some specialized version of the above class};
someObject.addComponent(new SomeComponent());
someObject.addComponent(new SomeSpecialComponent());
//This could retrieve either component
SomeComponent * sc1 = someObject.getComponent<SomeComponent*>();
//This fails
SomeComponent * sc1 = someObject.getComponent<SomeSpecialComponent*>();
How can I redesign this method to ensure the correct component is being returned?
Thanks
I think there are some design issues here, but it's difficult to help because there is no approach for me to recreate your code. Maybe you could post all your functions which have to do with your problem, not only those you think they don't work properly.
But I will try my best. At first, as already mentioned your dynamic_cast is a bad design, because "GetComponent" will likely often get called and dynamic_cast's are really expensive. I would try using a base Component class, like Unity really does it. If you handle those Components like the most game engines does, with a base class from which you derive from, you have a lot more control and can optimize better than with your approach. You only have to write the base component class in your game engine and let all other classes derive from this class. If you provide the functions you really need in your engine code you won't have any problem with that. Then you only need to expose this class to the game which should get created with your engine.
If you need some example, download Unreal Engine source code which is open source and study a bit of it and I think you will learn a lot from that.
I would give the "addComponent" function a try or maybe the container you want to store the component, because maybe it checks if the component is already contained and if they have the same base class and the check isn't properly written, the container just never receives the class you want to add.
If you already checked that it would be nice to know how you detect, that your second function fails? Did you get a nullptr or did you get an error message? If you receive a nullptr out of the function try to debug your code and write a more detailed description of what happens here.
Inheritance is a "is a" relationship, so if A inherits from B and C from B it means B is a A and C is a B. So if you have an C*-object then the object behind C* literally also is a B* and a A*. There is no none hacky way to distinguish new B() and new C() object by dynamic_casting it to B*, because both of those types are a B*.
But one solution with a big drawback to your problem could be to declare your child classes as final and the parent classes with at least one pure virtual function. I guess the drawback is self explanatory.

Alternate ways to identify polymorphic objects?

I've been searching all through the web and I seem to not find any alternate way of doing comparing if two polymorphic objects are the same type, or if a polymorphic object IS a type. The reason for this is because I am going to implement a Entity System inside of my game that I am currently creating.
I have not found another way of doing this other than with the use macros or a cast (the cast not being a portable method of doing so). Currently this is how I am identifying objects, is there a more efficient or effective way of doing this? (without the use of C++ RTTI)
I pasted it on pastebin, since pasting it here is just too much of a hassle.
http://pastebin.com/2uwrb4y2
And just incase you still do not understand exactly what I'm trying to achieve, I'll try to explain it. An entity in a game is like an object inside of the game (e.g. a player or enemy), it have have components attached to it, these components are data for an entity. A system in the entity system is what brings the data and logic of the game together.
For example, if I wanted to display a model up on the screen it would be similar to this:
World world; // Where all entities are contained
// create an entity from the world, and add
// some geometry that is loaded from a file
Entity* e = world.createEntity();
e->add(new GeometryComponent());
e->get<GeometryComponent>()->loadModel("my_model.obj"); // this is what I want to be able to do
world.addSystem(new RenderingSystem());
// game loop
bool isRunning = true;
while(isRunning)
{
pollInput();
// etc...
// update the world
world.update();
}
EDIT:
Here's a framework, programmed in Java, that does mainly what I want to be able to do.
http://gamadu.com/artemis/tutorial.html
See std::is_polymorphic. I believe boost has it too.
If T is a polymorphic class (that is, a class that declares or inherits at least one virtual function), provides the member constant value equal true. For any other type, value is false.
http://en.cppreference.com/w/cpp/types/is_polymorphic
Edit:
Why can't you just do this in your example?
Entity* e = world.createEntity();
GemoetryComponent* gc = new GeometryComponent();
gc->loadModel("my_model.obj");
e->add(gc);
Create the structure before stripping the type information.
If you're determined not to use C++'s built-in RTTI, you can reimplement it yourself by deriving all classes from a base class that contains a virtual method:
class Base {
public:
virtual string getType() = 0;
};
Then every derived class needs to overload this method with a version that returns a distinct string:
class Foo : public Base {
public:
string getType() { return "Foo"; }
};
You can then simply compare the results of calling getType() on each object to determined if they are the same type. You could use an enumeration instead of a string if you know up front all the derived classes that will ever be created.
Entity* e = world.createEntity();
e->add(new GeometryComponent());
e->get<GeometryComponent>()->loadModel("my_model.obj");
// this is what I want to be able to do
First the simple: there is a base type to all of the components that can be added, or else you would not be able to do e->add(new GeometryComponent()). I assume that this particular base has at least one virtual function, in which case the trivial solution is to implement get as:
template <typename T>
T* get() {
return dynamic_cast<T*>(m_component); // or whatever your member is
}
The question says that you don't want to use RTTI, but you fail to provide a reason. The common misundertandings are that RTTI is slow, if that is the case, consider profiling to see if that is your case. In most cases the slowness of dynamic_cast<> is not important, as dynamic_casts should happen rarely on your program. If dynamic_cast<> is a bottleneck, you should refactor so that you don't use it which would be the best solution.
A faster approach, (again, if you have a performance bottleneck here you should redesign, this will make it faster, but the design will still be broken) if you only want to allow to obtain the complete type of the object would be to use a combination of typeid to tests the type for equality and static_cast to perform the downcast:
template <typename T>
T* get() {
if (typeid(*m_component)==typeid(T))
return static_cast<T*>(m_component);
else
return 0;
}
Which is a poor man's version of dynamic_cast. It will be faster but it will only let you cast to the complete type (i.e. the actual type of the object pointed, not any of it's intermediate bases).
If you are willing to sacrifice all correctness (or there is no RTTI: i.e. no virtual functions) you can do the static_cast directly, but if the object is not of that type you will cause undefined behavior.

runtime type comparison

I need to find the type of object pointed by pointer.
Code is as below.
//pWindow is pointer to either base Window object or derived Window objects like //Window_Derived.
const char* windowName = typeid(*pWindow).name();
if(strcmp(windowName, typeid(Window).name()) == 0)
{
// ...
}
else if(strcmp(windowName, typeid(Window_Derived).name()) == 0)
{
// ...
}
As i can't use switch statement for comparing string, i am forced to use if else chain.
But as the number of window types i have is high, this if else chain is becoming too lengthy.
Can we check the window type using switch or an easier method ?
EDIT: Am working in a logger module. I thought, logger should not call derived class virtual function for logging purpose. It should do on its own. So i dropped virtual function approach.
First of all use a higher level construct for strings like std::string.
Second, if you need to check the type of the window your design is wrong.
Use the Liskov substitution principle to design correctly.
It basically means that any of the derived Window objects can be replaced with it's super class.
This can only happen if both share the same interface and the derived classes don't violate the contract provided by the base class.
If you need some mechanism to apply behavior dynamically use the Visitor Pattern
Here are the things to do in order of preference:
Add a new virtual method to the base class and simply call it. Then put a virtual method of the same name in each derived class that implements the corresponding else if clause inside it. This is the preferred option as your current strategy is a widely recognized symptom of poor design, and this is the suggested remedy.
Use a ::std::map< ::std::string, void (*)(Window *pWindow)>. This will allow you to look up the function to call in a map, which is much faster and easier to add to. This will also require you to split each else if clause into its own function.
Use a ::std::map< ::std::string, int>. This will let you look up an integer for the corresponding string and then you can switch on the integer.
There are other refactoring strategies to use that more closely resemble option 1 here. For example,if you can't add a method to the Window class, you can create an interface class that has the needed method. Then you can make a function that uses dynamic_cast to figure out if the object implements the interface class and call the method in that case, and then handle the few remaining cases with your else if construct.
Create a dictionary (set/hashmap) with the strings as keys and the behaviour as value.
Using behaviour as values can be done in two ways:
Encapsulate each behaviour in it's
own class that inherit from an
interface with"DoAction" method that
execute the behavior
Use function pointers
Update:
I found this article that might be what you're looking for:
http://www.dreamincode.net/forums/topic/38412-the-command-pattern-c/
You might try putting all your typeid(...).name() values in a map, then doing a find() in the map. You could map to an int that can be used in a switch statement, or to a function pointer. Better yet, you might look again at getting a virtual function inside each of the types that does what you need.
What you ask for is possible, it's also unlikely to be a good solution to your problem.
Effectively the if/else if/else chain is ugly, the first solution that comes to mind will therefore to use a construct that will lift this, an associative container comes to mind and the default one is obviously std::unordered_map.
Thinking on the type of this container, you will realize that you need to use the typename as the key and associate it to a functor object...
However there are much more elegant constructs for this. The first of all will be of course the use of a virtual method.
class Base
{
public:
void execute() const { this->executeImpl(); }
private:
virtual void executeImpl() const { /* default impl */ }
};
class Derived: public Base
{
virtual void executeImpl() const { /* another impl */ }
};
It's the OO way of dealing with this type of requirement.
Finally, if you find yourself willing to add many different operations on your hierarchy, I will suggest the use of a well-known design pattern: Visitor. There is a variation called Acyclic Visitor which helps dealing with dependencies.

How to typeof in C++

How to simulate C# typeof-command behavior in C++?
C# example:
public static PluginNodeList GetPlugins (Type type)
{
...
}
Call:
PluginManager.GetPlugins (typeof(IPlugin))
How to implement this using C++? Maybe QT or Boost libraries provide a solution?
What about the case if you want to implement .GetPlugins(...) in a way that it loads those kinds of objects from a file (.so or .dll)?
You could use a dynamic_cast to test types as shown below:
IPlugin* iPluginPtr = NULL;
iPluginPtr = dynamic_cast<IPlugin*>(somePluginPtr);
if (iPluginPtr) {
// Cast succeeded
} else {
// Cast failed
}
This behaviour is called RTTI (Run time type information). This technique is best to be avoided, but can be beneficial in some situations.
There are two big ways to solve this. The first way is to write an interface with a pure virtual function that returns a class specific integer reference code. This code can then be used to represent a specific type. These integers could be stored in a specific enumeration.
In derived classes you can then override the method and return that class specific type.
During runtime, you can then call Plugin->getType() for instance, and it'll return its specific type. You can then perform a static_cast on the pointer to get the correct pointer of the derived type back.
The second way is to either use typeid to get the classtype of the object; but this is compiler dependant. You can also try casting your pointer using dynamic_cast; dynamic_cast returns a null pointer when it's being cast into the wrong type; and a valid one when being cast in a correct type. The dynamic cast method has a bigger overhead tho than the getType method described above.
If you want complete typeof-like behaviour, you would have to use RTTI (run-time type information). On many compilers you have to explicitly activate usage of RTTI, as it incurs run-time overhead.
Then you can use typeid or dynamic_cast to find an object's type.
If you don't want to use typeid, you'd have to use inheritance, pointers and/or overloads. Boost might help you, but it's not too hard.
Example 1:
class Iplugin { ... }
class Plugin1 : public Iplugin { ... }
class Plugin2 : public Iplugin { ... }
void getplugins(Iplugin* p) {
// ... you don't know the type, but you know
// what operations it supports via Iplugin
}
void getplugins(Plugin1& p) {
// expliticly handle Plugin1 objects
}
As you can see there are several ways of avoiding usage of RTTI and typeid.
Designing around this problem would be the best choice. Good use of object orientation can usually help but you can always create your own system for querying the type of an object by using a base class which stores an identifier for each object, for instance.
Always try to avoid using dynamic_cast as it most often uses string comparison to find the type of an object and that makes it really slow.
You can use typeof() in GCC. With other compilers, it's either not supported or you have to do crazy template mangling or use "bug-features" that are very compiler specific (like the way Boost does it).
Boost does have a typeof. C++ 0x doesn't call it typeof, but has both 'auto' and 'decltype' that provide the same kinds of functionality.
That said, I'm pretty sure none of those provides what you're really looking for in this case -- at most, they provide only a small piece of what you need/want overall.
Surely you would just use overloading?
static PluginManager::GetPlugins(Type1 &x) {
// Do something
}
static PluginManager::GetPlugins(Type2 &x) {
// Do something else
}
and then call:
PluginManager::GetPlugins(IPlugin);
Not directly answering the "how to get typeof() in C++", but I infer from your question that you are looking at how to do plugins in C++. If that's the case, you may be interested in the (not-yet)Boost.Extension library, and maybe in its reflection part.

A more generic visitor pattern

I'm sorry if my question is so long and technical but I think it's so important other people will be interested about it
I was looking for a way to separate clearly some softwares internals from their representation in c++
I have a generic parameter class (to be later stored in a container) that can contain any kind of value with the the boost::any class
I have a base class (roughly) of this kind (of course there is more stuff)
class Parameter
{
public:
Parameter()
template typename<T> T GetValue() const { return any_cast<T>( _value ); }
template typename<T> void SetValue(const T& value) { _value = value; }
string GetValueAsString() const = 0;
void SetValueFromString(const string& str) const = 0;
private:
boost::any _value;
}
There are two levels of derived classes:
The first level defines the type and the conversion to/from string (for example ParameterInt or ParameterString)
The second level defines the behaviour and the real creators (for example deriving ParameterAnyInt and ParameterLimitedInt from ParameterInt or ParameterFilename from GenericString)
Depending on the real type I would like to add external function or classes that operates depending on the specific parameter type without adding virtual methods to the base class and without doing strange casts
For example I would like to create the proper gui controls depending on parameter types:
Widget* CreateWidget(const Parameter& p)
Of course I cannot understand real Parameter type from this unless I use RTTI or implement it my self (with enum and switch case), but this is not the right OOP design solution, you know.
The classical solution is the Visitor design pattern http://en.wikipedia.org/wiki/Visitor_pattern
The problem with this pattern is that I have to know in advance which derived types will be implemented, so (putting together what is written in wikipedia and my code) we'll have sort of:
struct Visitor
{
virtual void visit(ParameterLimitedInt& wheel) = 0;
virtual void visit(ParameterAnyInt& engine) = 0;
virtual void visit(ParameterFilename& body) = 0;
};
Is there any solution to obtain this behaviour in any other way without need to know in advance all the concrete types and without deriving the original visitor?
Edit: Dr. Pizza's solution seems the closest to what I was thinking, but the problem is still the same and the method is actually relying on dynamic_cast, that I was trying to avoid as a kind of (even if weak) RTTI method
Maybe it is better to think to some solution without even citing the visitor Pattern and clean our mind. The purpose is just having the function such:
Widget* CreateWidget(const Parameter& p)
behave differently for each "concrete" parameter without losing info on its type
For a generic implementation of Vistor, I'd suggest the Loki Visitor, part of the Loki library.
I've used this ("acyclic visitor") to good effect; it makes adding new classes to the hierarchy possible without changing existing ones, to some extent.
If I understand this correctly...
We had a object that could use different hardware options. To facilitate this we used a abstract interface of Device. Device had a bunch of functions that would be fired on certain events. The use would be the same but the various implementations of the Device would either have a fully-fleshed out functions or just return immediately. To make life even easier, the functions were void and threw exceptions on when something went wrong.
For completeness's sake:
it's of course completely possible to write an own implementation of a multimethod pointer table for your objects and calculate the method addresses manually at run time. There's a paper by Stroustrup on the topic of implementing multimethods (albeit in the compiler).
I wouldn't really advise anyone to do this. Getting the implementation to perform well is quite complicated and the syntax for using it will probably be very awkward and error-prone. If everything else fails, this might still be the way to go, though.
I am having trouble understanding your requirements. But Ill state - in my own words as it were - what I understand the situation to be:
You have abstract Parameter class, which is subclassed eventually to some concrete classes (eg: ParameterLimitedInt).
You have a seperate GUI system which will be passed these parameters in a generic fashion, but the catch is that it needs to present the GUI component specific to the concrete type of the parameter class.
The restrictions are that you dont want to do RTTID, and dont want to write code to handle every possible type of concrete parameter.
You are open to using the visitor pattern.
With those being your requirements, here is how I would handle such a situation:
I would implement the visitor pattern where the accept() returns a boolean value. The base Parameter class would implement a virtual accept() function and return false.
Concrete implementations of the Parameter class would then contain accept() functions which will call the visitor's visit(). They would return true.
The visitor class would make use of a templated visit() function so you would only override for the concrete Parameter types you care to support:
class Visitor
{
public:
template< class T > void visit( const T& param ) const
{
assert( false && "this parameter type not specialised in the visitor" );
}
void visit( const ParameterLimitedInt& ) const; // specialised implementations...
}
Thus if accept() returns false, you know the concrete type for the Parameter has not implemented the visitor pattern yet (in case there is additional logic you would prefer to handle on a case by case basis). If the assert() in the visitor pattern triggers, its because its not visiting a Parameter type which you've implemented a specialisation for.
One downside to all of this is that unsupported visits are only caught at runtime.