Virtual vs. Template (C++)

Virtual

Gets resolved at run-time, leading to a shorter compile-time.

#include <iostream>
 
class Animal
{
public:
    virtual void makeSound() = 0;
};
 
class Cow : public Animal
{
public:
    void makeSound() { std::cout << "Moo" << std::endl; };
};
 
int main()
{
    Cow cow;
    cow.makeSound();
 
    return 0;
}

Template

Gets resolved at compile-time, leading to a shorter run-time.

#include <iostream>
 
template <typename T>
class Animal
{
public:
    void makeSound() { t.makeSound(); };
 
private:
    T t;
};
 
class Cow
{
public:
    void makeSound() { std::cout << "Moo" << std::endl; };
};
 
int main()
{
    Animal<Cow> cow;
    cow.makeSound();
 
    return 0;
}