How to compare types ?

This is a discussion on How to compare types ? within the C++ Programming forums, part of the General Programming Boards category; Hi! I have sucha situation: Code: class a { vector<int> v1; vector<some_type> v2; vector<some_type2> v3; public: template <class T> void ...

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    76

    How to compare types ?

    Hi!
    I have sucha situation:
    Code:
    class a
    {
            vector<int> v1;
            vector<some_type> v2;
            vector<some_type2> v3;
    public: 
            template <class T> void f(T a)
            {
                    // here I would like to check T if it is int,
                    // and if it is then do v1.push_back(a);
                    // and do the same if T is some_type or some_type2
            }
    };
    Is is possible to do something like this ?
    Best regards.

  2. #2
    Massively Single Player AverageSoftware's Avatar
    Join Date
    May 2007
    Location
    Buffalo, NY
    Posts
    141
    You can pull that off using the typeid() operator, but this might be more efficient:

    Code:
    template <class T> void f(T a)
    {
        //Do the some_type and some_type2 stuff here.
    }
    
    template <> void f<int>(int a)
    {
        //Do the int stuff.
    }
    This is called a template specialization, and works well for these circumstances.

  3. #3
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,262
    typeid might be what you're looking for.

    Code:
    int main( void )
    {
        int i;
        char c;
        
        if ( typeid(i) == typeid(c) )
            std::cout<< "Tyeps the same";
        else 
            std::cout<< "Not the same!";
    
        std::cout<< typeid(i).name();
        std::cout<< typeid(c).name();
    
    
        return 0;
    }
    Ah, I'm beat.

  4. #4
    Registered User
    Join Date
    May 2005
    Posts
    76
    Thanks for replies. In this time I will use template specialization.
    Best regards.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. invalid types 'int[int]' for array subscript
    By kolistivra in forum C++ Programming
    Replies: 6
    Last Post: 12-11-2010, 11:57 AM
  2. Replies: 6
    Last Post: 08-23-2008, 01:16 PM
  3. compare if 2 string types are equal
    By sujeet1 in forum C++ Programming
    Replies: 4
    Last Post: 06-06-2007, 06:37 PM
  4. The Interactive Animation - my first released C program
    By ulillillia in forum A Brief History of Cprogramming.com
    Replies: 48
    Last Post: 05-10-2007, 02:25 AM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21