RTTI in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ashitpro
    Recognized Expert Contributor
    • Aug 2007
    • 542

    RTTI in C++

    consider Following pseudocode...

    display(x)
    {
    if x is of type int
    print "integer found"
    if x is of type float
    print "Float found"
    }
    main()
    {
    //few declarations.
    display(x);

    }

    We can achieve this is Python or Ruby easily.
    I have problem in C++.
    Although, We can use "typeid(variabl e_name).name()" to get the class name.,
    We get trapped while declaring the above "display" function as.

    display(int or float or somthing_else);

    because at the time of declaration we never know, what kind of variable will be.

    So, In short How can I achieve this in C++?

    Don't say that It can't be done in C++.
    Ofcourse this may not be a challenge for some people.
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by ashitpro
    consider Following pseudocode...

    display(x)
    {
    if x is of type int
    print "integer found"
    if x is of type float
    print "Float found"
    }
    main()
    {
    //few declarations.
    display(x);

    }

    We can achieve this is Python or Ruby easily.
    I have problem in C++.
    Although, We can use "typeid(variabl e_name).name()" to get the class name.,
    We get trapped while declaring the above "display" function as.

    display(int or float or somthing_else);

    because at the time of declaration we never know, what kind of variable will be.

    So, In short How can I achieve this in C++?

    Don't say that It can't be done in C++.
    Ofcourse this may not be a challenge for some people.
    Moved to C++ forum

    Comment

    • Banfa
      Recognized Expert Expert
      • Feb 2006
      • 9067

      #3
      use a template function and specialise it for the basic types.

      The reason this is not as easy as it is in those scripting languages is that C++ has strong typing, that is variables have to be given a type when they are declared so there is never any question as to what there type is so it is rarely necessary to have code that makes this determination.

      Comment

      Working...