tags:

views:

235

answers:

3
  class A {}
  A a;
  type_info info = typeid (a); // error type_info is private

i want a list list<type_info> to store the type of classes. Is there a solution?

+2  A: 

You cannot instantiate objects of the type_info class directly, because the class has only a private copy constructor. Since the list needs copy constructor...

If you really need it, use std::list< type_info*>.

I don't know why you need this list, but I would think to an alternative design, not involving RTTI, if possible.

Cătălin Pitiș
actually my intent is to make a map<typeinfo, typeinfo>. Given a typeinfo instantiating another type.sample usage :Get(typeof(PageA)) gives me a StyleA class
jack london
Then you should really use someting like class ids which you create yourself.
Simon H.
If you know that you're dealing with PageA's at compile time, you should put a typedef inside PageA. Example: class PageA { public: typedef StyleA style_t; //.... };Then when you want to instantiate the appropriate Style, you just do: "PageA::style_t mystyleinstance;".
Joseph Garvin
I seem to remember getting typeid for non-polymorphic types just OK (including built-ins). Of course, I don't see how one would use such a map to instantiate anything. I think OP might also look into the factory patterns.
UncleBens
The "only for polymorphic" part is not true. 'type_info' is generated for all types. No exceptions. The only thing that is specific for polymorphic types is that for polymorphic types 'typeid' will identify *dynamic* type of the object, while for non-polymorphic other types it describes *static* type of the object. "Enabling/disabling RTTI" is a compiler-specific feature, that doesn't exist at the language level. Normally, disabling RTTI will simply make 'typeid' return static type for polymorphic classes.
AndreyT
You're right. My mistake. Updated
Cătălin Pitiș
+1  A: 

You can't create copies of 'type_info' objects. However, the result if 'typeid' is an Lvalue and the corresponding 'type_info' objects, once obtained, continue to live till the end of the program. For these reasons, you can safely store pointers to 'type_info' objects in your list.

AndreyT
A: 

From your comment to Cătălin Pitiș' answer, I understand that your goal is to write a function that returns a different "Style" type for different "Page" types. Does this have to be dynamic? If not, would something like this do what you want?

template<class PageT>
struct StyleOf;

template<>
struct StyleOf<PageA>{
    typedef StyleA type;
};

template<>
struct StyleOf<PageB>{
    typedef StyleB type;
};

// etc...

template<class PageT>
typename StyleOf<PageT>::type
GetStyle(const PageT&){
    return StyleOf<PageT>::type();
}

Or, with Boost.MPL:

using boost::mpl::map;
using boost::mpl::pair;

typedef map<
    pair<PageA, StyleA>,
    pair<PageB, StyleB>,
    //etc.
>
PageToStyle;

Getting the Style type from the Page type is:

boost::mpl::at<PageToStyle, Page>::type;
Éric Malenfant