How to typeof in C++ - 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.

Related

Enforce type safety in C++ without using extra classes

I am somewhat familiar with type safety, and have used it successfully before in methods which receive several parameters of the same type (bool) to avoid confusion. For example:
// Old version of the method
void sendPackage(bool sendImmediately, bool dividePacket);
// Type safe version
enum SendImmediatelyPreference
{
SEND_IMMEDIATELY,
DO_NOT_SEND_IMMEDIATELY
};
enum PacketDivisionPreference
{
DIVIDE_PACKET,
DO_NOT_DIVIDE_PACKET
};
void sendPackage(
SendImmediateltPreference immediatePref,
PacketDivisionPreference divisionPref);
So the cryptic sendPackage(true, false) becomes sendPackage(SEND_IMMEDIATELY, DO_NOT_DIVIDE_PACKET).
The problem is that this is only an option for bool. I have a method that accepts several std::vector<std::string> and I'd like to minimise the posibility of the user inputting the arguments in the wrong order.
I can think of creating different classes which contains an std::vector<std::string> and either override tons of the std::vector methods or expose the internal vector.
Is there an easier way, some sort of typedef which enforces type safety? Using boost would be okay.
How about an alternative approach using named parameters? There are several ways of going about this in C++ described here. The tag approach using a tuple looks reasonable. There is also boost parameter.
This doesn't offer strong type safety, but you could argue that the user is just as likely to call the wrong constructor to make their type safe object as they are to use the wrong tag when calling your function. This situation is less likely to occur if the types are used throughout your application vs defined only for one particular function.
See also the discussion of boost strong typedef vs parameter for a similar purpose here.
Not sure I understood you correctly, but maybe this can help:
enum SendImmediatelyPreference : bool // allows only 2 options:
{
DO_NOT_SEND_IMMEDIATELY, // false
SEND_IMMEDIATELY // true
}
What about creating a class that inherits (public) from std::vector to have a strong typecheck. The advantage is that you only need to rewrite constructors..
You can also regroup your parameters in a std::unordered_map>, to implement argument as a dict (like in python, or javascript)
BOOST_STRONG_TYPEDEF is precisely a typedef which enforces type safety.
However, this answer provides some caveats related to using this strong typedef for just a function, and argues that the types should be used all over the code to prevent unnecessary castings.
I like to bundle the parameters in a config class or struct. For example:
struct SendOptions
{
bool send_immediately = false;
bool divide_packet = false;
// ...
};
void sendPackage(SendOptions options);
This has the additional advantage the extra options can be added later without needing to change the interface of sendPackage(SendOptions).
This does not increase type safety but it does help to prevent errors (especially if there are a lot of parameters), which is probably the goal you're trying to achieve.

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.

Using dynamic typing in D, a statically typed language

I was implementing a dynamic typing library for D when I ran across an interesting problem.
Right now, I've succeeded in making a function called dynamic() which returns a dynamic version of an object.
For example:
import std.stdio, std.dynamic.core;
class Foo
{
string bar(string a) { return a ~ "OMG"; }
int opUnary(string s)() if (s == "-") { return 0; }
}
void main(string[] argv)
{
Dynamic d = dynamic(new Foo());
Dynamic result = d.bar("hi");
writeln(result); // Uh-oh
}
The problem I've run across is the fact that writeln tries to use compile-time reflection to figure out how to treat result.
What's the first thing it tries? isInputRange!(typeof(result))
The trouble is, it returns true! Why? Because I have to assume that all members which it needs exist, unless I can prove otherwise at run time -- which is too late. So the program tries to call front, popFront, and empty on result, crashing my program.
I can't think of a way to fix this. Does anyone have an idea?
You are trying to make two fundamentally different concepts work together, namely templates and dynamic typing. Templates rely very much on static typing, isInputRange works by checking which attributes or methods a type has. Your dynamic type is treated as having every attribute or method at compile time, ergo it is treated as fulfilling every static duck-typing interface.
Therefore, to make Dynamic work in a statically typed environment, you have to provide more static information at some places.
Some solutions I can see:
provide your own dynamically typed implementations for heavily used functions. The whole problem you are having is caused by the fact that you are trying to use generic functions that assume static typing with dynamic types.
explicitly make dynamic a range of char, and care for the conversion to string of the underlying data yourself. (You'd have to have a custom toString method anyways if the isInputRange issue would not exist, because otherwise its result would again be of Dynamic type). This would probably make writeln(d); work.
provide wrappers for dynamic that allow you to pass dynamic types into various templated functions. (Those would just exhibit a static interface and forward all calls to Dynamic).
Eg:
Dynamic d;
// wrap d to turn it into a compile-time input range (but NOT eg a forward range)
Dynamic d2=dynamic(map!q{a*2}(dynInputRange(d)));
// profit
4 . Add a member template to Dynamic, which allows to statically disable some member function names.
Eg:
static assert(!isForwardRange!(typeof(d.without!"save")));
what is wrong with using std.variant which implements all you need for dynamic typing (along with quite a bit of syntactic sugar)
Could you provide an overload for isInputRange? Something like this (note that I haven't looked at the implementation of isInputRange):
template isInputRange(T : Dynamic) {
enum isInputRange = false;
}
If this is provided by your dynamic.core, I think this overload should be chosen before the std lib one.
For the general case Dynamic has to accept any method lookup at compile time, as you said. Suppose for a moment that you could prevent the isInputRange predicate to evaluate to true, now the wrong code will be generated when you try to create a Dynamic from an input range.
I don't think this is fixable, at least not in a general way. In this particular case the best solution I can think of is that Dynamic provides it's own version of toString, and writeln would prefer that over the inputRange specialization. I believe writeln doesn't do this at the moment, at least not for structs, but it probably should.
Another compromise would be to disallow a few methods such as popFront in the opDispatch constraint, instead Dynamic would provide opIndex or a member object to access these special cases. This might not be as bad as it sounds, because the special cases are rare and using them would result in an obvious compiler error.
I think that the best way to salvage this kind of method resolution for Dynamic is to fix writeln and accept that Dynamic will not work with all templated code.
Have you looked into std.variant?
import std.stdio, std.variant;
class Foo {
string Bar(string a) {
return a ~ " are Cool!";
}
}
void main() {
Variant foo = new Foo();
Variant result = foo.peek!Foo.Bar("Variants");
writeln(result); // Variants are Cool!
}
http://www.d-programming-language.org/phobos/std_variant.html

Can a "type" be passed in C++?

[A follow up to this question: Possible to instantiate object given its type in C++?
In Java, you can have a method parameter of type Class, and callers can pass in Foo.class. I don't consider this aspect reflection, though what you can do with the passed-in Class obviously is. Does C++ have any mechanism for passing in a "type"? Since I know there is little/nothing I could do with that passed-in type, I suspect the answer is "no".
Obviously, templates provide this facility, but they're not what I'm looking for.
Sounds like RTTI (run-time type identification) is what you're looking for. From http://en.wikibooks.org/wiki/C++_Programming/RTTI :
The typeid operator, used to determine
the class of an object at runtime. It
returns a reference to a
std::type_info object, which exists
until the end of the program, that
describes the "object".
How about RTTI and typeid?
No. This feature is part of "reflection" and is only possible in languages like Java which actually put information about classes in the compiled binary.
C++ (typically) does not actually store any information about classes at all in the resulting binary. (Excepting a few bits necessary for std::type_info to work)
In reality, there's nothing like the "Type" provided by Java and friends available in C++, and therefore you cannot pass it to a method.
If you want to pass a type to a method for the purpose of instantiating it, you can actually do this in a better way (this works with Java and friends too)
#include <memory>
struct IMyType
{
virtual ~IMyType();
virtual MyMethod();
};
struct IElementFactory
{
virtual std::auto_ptr<IMyType> GetNewItem() const = 0;
virtual ~IElementFactory();
};
void MyMethodThatAcceptsAType(const IElementFactory& factory)
{
std::auto_ptr<IMyType> instance(factory.GetNewItem());
//Use your instance like normal.
}
This is better even in Java land because this code maintains type safety, while the reflection based code does not.

C++ checking the type of reference

Is it bad design to check if an object is of a particular type by having some sort of ID data member in it?
class A
{
private:
bool isStub;
public:
A(bool isStubVal):isStub(isStubVal){}
bool isStub(){return isStub;}
};
class A1:public A
{
public:
A1():A(false){}
};
class AStub:public A
{
public:
AStub():A(true){}
};
EDIT 1:
Problem is A holds a lot of virtual functions, which A1 doesn't override but the stub needs to, for indidicating that you are working on a stub instead of an actual object. Here maintainability is the question, for every function that i add to A, i need to override it in stub. forgetting it means dangerous behaviour as A's virtual function gets executed with stub's data. Sure I can add an abstract class ABase and let A and Astub inherit from them. But the design has become rigid enough to allow this refactor.
A reference holder to A is held in another class B. B is initialized with the stub reference, but later depending on some conditions, the reference holder in B is reinitialized with the A1,A2 etc.. So when i do this BObj.GetA(), i can check in GetA() if the refholder is holding a stub and then give an error in that case. Not doing that check means, i would have to override all functions of A in AStub with the appropriate error conditions.
Generally, yes. You're half OO, half procedural.
What are you going to do once you determine the object type? You probably should put that behavior in the object itself (perhaps in a virtual function), and have different derived classes implement that behavior differently. Then you have no reason to check the object type at all.
In your specific example you have a "stub" class. Instead of doing...
if(!stub)
{
dosomething;
}
Just call
object->DoSomething();
and have the implemention in AStub be a empty
Generally yes. Usually you want not to query the object, but to expect it to BEHAVE the proper way. What you suggest is basically a primitive RTTI, and this is generally frowned upon, unless there are better options.
The OO way would be to Stub the functionality, not check for it. However, in the case of a lot of functions to "stub" this may not seem optimal.
Hence, this depends on what you want the class to really do.
Also note, that in this case you don't waste space:
class A
{
public:
virtual bool isStub() = 0;
};
class A1:public A
{
public:
virtual bool isStub() { return false; };
};
class AStub:public A
{
public:
virtual bool isStub() { return true; };
};
... buuut you have a virtual function -- what usually is not a problem, unless it's a performance bottleneck.
If you want to find out the type of object at runtime you can use a dynamic_cast. You must have a pointer or reference to the object, and then check the result of the dynamic_cast. If it is not NULL, then the object is the correct type.
With polymorphic classes you can use the typeofoperator to perform RTTI. Most of the time you shouldn't need to. Without polymorphism, there's no language facility to do so, but you should need to even less often.
One caveat. Obviously your type is going to be determined at construction time. If your determination of 'type' is a dynamic quantity you can't solve this problem with the C++ type system. In that case you need to have some function. But in this case it is better to use the overridable/dynamic behavior as Terry suggested.
Can you provide some better information as what you are trying to accomplish?
This sort of thing is fine. It's generally better to put functionality in the object, so that there's no need to switch on type -- this makes the calling code simpler and localises future changes -- but there's a lot to be said for being able to check the types.
There will always be exceptions to the general case, even with the best will in the world, and being able to quickly check for the odd specific case can make the difference between having something fixed by one change in one place, a quick project-specific hack in the project-specific code, and having to make more invasive, wide-reaching changes (extra functions in the base class at the very least) -- possibly pushing project-specific concerns into shared or framework code.
For a quick solution to the problem, use dynamic_cast. As others have noted, this lets one check that an object is of a given type -- or a type derived from that (an improvement over the straightforward "check IDs" approach). For example:
bool IsStub( const A &a ) {
return bool( dynamic_cast< const AStub * >( &a ) );
}
This requires no setup, and without any effort on one's part the results will be correct. It is also template-friendly in a very straightforward and obvious manner.
Two other approaches may also suit.
If the set of derived types is fixed, or there are a set of derived types that get commonly used, one might have some functions on the base class that will perform the cast. The base class implementations return NULL:
class A {
virtual AStub *AsStub() { return NULL; }
virtual OtherDerivedClass *AsOtherDerivedClass() { return NULL; }
};
Then override as appropriate, for example:
class AStub : public A {
AStub *AsStub() { return this; }
};
Again, this allows one to have objects of a derived type treated as if they were their base type -- or not, if that would be preferable. A further advantage of this is that one need not necessarily return this, but could return a pointer to some other object (a member variable perhaps). This allows a given derived class to provide multiple views of itself, or perhaps change its role at runtime.
This approach is not especially template friendly, though. It would require a bit of work, with the result either being a bit more verbose or using constructs with which not everybody is familiar.
Another approach is to reify the object type. Have an actual object that represents the type, that can be retrieved by both a virtual function and a static function. For simple type checking, this is not much better than dynamic_cast, but the cost is more predictable across a wide range of compilers, and the opportunities for storing useful data (proper class name, reflection information, navigable class hierarchy information, etc.) are much greater.
This requires a bit of infrastructure (a couple of macros, at least) to make it easy to add the virtual functions and maintain the hierarchy data, but it provides good results. Even if this is only used to store class names that are guaranteed to be useful, and to check for types, it'll pay for itself.
With all this in place, checking for a particular type of object might then go something like this example:
bool IsStub( const A &a ) {
return a.GetObjectType().IsDerivedFrom( AStub::GetClassType() );
}
(IsDerivedFrom might be table-driven, or it could simply loop through the hierarchy data. Either of these may or may not be more efficient than dynamic_cast, but the approximate runtime cost is at least predictable.)
As with dynamic_cast, this approach is also obviously amenable to automation with templates.
In the general case it might not be a good design, but in some specific cases it is a reasonable design choice to provide an isStub() method for the use of a specific client that would otherwise need to use RTTI. One such case is lazy loading:
class LoadingProxy : IInterface
{
private:
IInterface m_delegate;
IInterface loadDelegate();
public:
LoadingProxy(IInterface delegate) : m_delegate(delegate){}
int useMe()
{
if (m_delegate.isStub())
{
m_delegate = loadDelegate();
}
return m_delegate.useMe();
}
};
The problem with RTTI is that it is relatively expensive (slow) compared with a virtual method call, so that if your useMe() function is simple/quick, RTTI determines the performance. On one application that I worked on, using RTTI tests to determine if lazy loading was needed was one of the performance bottlenecks identified by profiling.
However, as many other answers have said, the application code should not need to worry about whether it has a stub or a usable instance. The test should be in one place/layer in the application. Unless you might need multiple LoadingProxy implementations there might be a case for making isStub() a friend function.