Becks Wu
Becks Wu

Reputation: 21

C++ How to handle different class in a template

Below code generate error for complaining No member named a in Cat and No member named b in Dog

struct Dog{
    int a = 2;
};

struct Cat{
    int b = 3;
};

template <typename T>
void print( T* t){
    if (typeid(T) == typeid(Dog))
        cout << "Dog a "<<t->a<<endl;
    else if (typeid(T) == typeid(cat))
        cout <<" Cat b "<<t->b<<endl;
}

int main(int argc, const char * argv[]) {
    // insert code here...
    Dog * p1 = new Dog();
    print(p1);
    
    Cat * p2 = new Cat();
    print(p2);
    
    return 0;
}

Upvotes: 1

Views: 151

Answers (1)

Maxim Chetrusca
Maxim Chetrusca

Reputation: 3352

As others have pointed out, there are different ways to make it work.

This however, does not work because print() is not a function, but a function template. It's a blueprint for the concrete types. If you try to call print(Dog), what compiler does is, substitutes T with Dog:

void print( Dog* t){
if (typeid(Dog) == typeid(Dog))
    cout << "Dog a "<<t->a<<endl;
else if (typeid(Dog) == typeid(cat))
    cout <<" Cat b "<<t->b<<endl;
}

Now, this would not compile for obvious reasons - Dog does not have the member b. The else branch is false, but this does not warrant to write code that does not compile there. (And by the way, you misspelled the class Cat there). Same for Cats instantiation.

Upvotes: 3

Related Questions