0

In C++, we are allowed to have two functions of the same name provided that the function parameter lists are different.

This is called, "overloading."

#include <iostream>
using namespace std;

float foo(float var){
    // OVERLOADED FUNCTION
    return 10.0;
}

int foo(int var) {
    // OVERLOADED FUNCTION
    return 0;
}

int main() {
    
    cout << foo(-5) << endl;

    cout foo(5.5f) << endl;
    return 0;
}

I was wondering, are we allowed to have two template classes of the same name, so long as the lists of parameters to the template classes are different?

#include <iostream>
using namespace std;

template<typename SpamType>
class Klaus
{
    public:
        SpamType mySpam;
        
        void print () {
            cout << "SPAM" << endl;
            return 0;
        }
};

template<int Whites, int Yolks>
class Klaus
{
    public:
        int myEggs[Whites][Yolks];
        
        void print () {
            cout << "EGGS" << endl;
            return 0;
        }
};

int main()
{
    Klaus<2, 5>   eggKlaus;
    Klaus<float>  spamKlaus;
    
    eggKlaus.print();  // prints `EGGS`
    spamKlaus.print(); // prints `SPAM`
 
    return 0;
}
Samuel Muldoon
  • 1,224
  • 3
  • 17
  • Pretty sure sending the posted code through a compiler would tell you your answer one way or another. – WhozCraig Dec 13 '20 at 04:52
  • I'll vote to close - because the other answer gives a lot of technical reasons (and a few aesthetic decisions and rationales) - but I think it's an insightful question to have asked. – Brett Hale Dec 13 '20 at 05:51

0 Answers0