1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Retrieving the type from a typedef

Discussion in 'C++' started by a_new_beginning, Aug 15, 2008.

  1. a_new_beginning

    a_new_beginning New Member

    Joined:
    Jul 27, 2008
    Messages:
    3
    Likes Received:
    0
    Trophy Points:
    0
    Hello. My question is as follows: is it possible to retrieve the type from a typedef in a generic fashion?
    e.g., vector<int>::value_type will return the int type.

    However, suppose we write:

    typedef pair<string, string> pstring;

    pstring.first::value_type &string1 (.....);
    pstring.second::value_type &string2 (.....);

    Now I understand first_type and second_type are defined for pair,
    but I'm looking to find whether there is a general solution that would work for the built-in types
    analogously to how the value_type container typedef works for element types.... i.e.,

    typedef int Integer
    Integer::value_type int1 (.....);

    Is this possible?
    Or is it simply a good reason to stay away from typedefs of primitive built-in types?
     
  2. imported_xpi0t0s

    imported_xpi0t0s New Member

    Joined:
    Jul 18, 2008
    Messages:
    101
    Likes Received:
    0
    Trophy Points:
    0
    The built-in types don't have any kind of runtime type information (RTTI). You can define your own datatypes using struct, e.g. struct myType{int type; void *data; } (or use templates, which would be better) and implement RTTI in that way, if you want it.

    However you shouldn't write code that depends on the types of variables. Why do you want to know this, and what problem are you trying to solve? There's probably a better way to achieve what you want without relying on RTTI.

    I don't see the lack of RTTI as a reason to stay away from typedefs of primitives. It's perfectly valid to have, e.g. typedef int YearNum; and desirable in some cases, for example typedef char NameStr[20]; defines NameStr as char[20]; supposing after some development you decide NameStr needs to be longer, changing this is a lot easier than checking the entire code for char[20]'s and changing them. Also this makes programming easier; instead of trying to remember the sizes for arrays of a particular type you just remember the type name.
     

Share This Page