سؤال

I've got a type_info object that defines type of property in my property map. I would like to run some piece of code (e.g. reading value from cin) parametrized with the type that is defined by my type_info object. It could be some template function, i.e.:

template<typename T>
void do_something()
{
  T a; cin >> a;
}

Then in some other part of code I would like to call it:

const type_info &type_description = foo.get_type_of_something();
do_some_magic(do_something, type_description);

I'm looking for the do_some_magic function that calls do_something specialized for type described by type_descriptor. The template function can be wrapped in some structure, it doesn't matter.

Of course it is possible only for finite set of types, defined in advance (since specialization must be generated for each at compile time).

One method is to make a chain of if(type_descriptor==typeid(int)) /*...*/ else if(type_descriptor==... and so on, but this is not very pretty solution (imo).

I'm wondering if there exist more clean solution? Or maybe some library ("boost" preferably) implements such mechanism already?

هل كانت مفيدة؟

المحلول

A type_info object presents you with information about an object at runtime. The only solution to your problem is comparing it to the result of the typeid operator to each of the target types.

Since you are looking for something pretty, you could make a map of type_info (wrapped, actually) to (boost|std)::function<>s.

نصائح أخرى

The simple case when you know the type at compile time, is to use functional overloading:

RETURN_TYPE_1 do_something_magic ( TYPE_1 ) { ... }

RETURN_TYPE_2 do_something_magic ( TYPE_2 ) { ... }

...

do_something_magic ( foo ); // just works as expected

You can extend the trick to multiple parameters as long as you know their type at compile time.

If you want to dispatch dynamicaly based on ONE argument type, in order to have type info you must use dynamic polymorphism, then simply use the RTTI and the native ability of C++ to dispatch based on the first type signature, the above code is still the good one provided that your have a virtual destructor ( non trivial destructor ) and the return type is the same for every overloaded functions.

If you want to dispatch dynamicaly based on several arguments types, the concern is quite different, you have to use a technic know as Mutimethod, it is well explained on Wikipedia, and boost provides an implementation.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top