- class myBaseClass
- {
- public:
- virtual void myMethod() { /* do fancy things */ }
- }
- class myDerivedClass : myBaseClass
- {
- public:
- virtual void myMethod() { /* do fancier things */ }
- }
- class myNonDerivedClass
- {
- public:
- void myMethod() { /* do unfancy things :( */ }
- }
- template <typename T>
- void myFunction(T parameter)
- {
- parameter.myMethod();
- }
- // Below are different main functions, each one which produces a different result.
- int main()
- {
- myFunction<myBaseClass>(someVariable);
- // This main function, *at compile time*, produces a new function like:
- // void myFunction_myBaseClass(myBaseClass parameter) { parameter.myMethod(); }
- // And then tries to compile it. Notice if you typed this code, there would be no compiler errors.
- }
- int main()
- {
- myFunction<myBaseClass>(someVariable);
- myFunction<myDerivedClass>(someOtherVariable);
- // This would make the compiler produce 2 functions:
- // void myFunction_myBaseClass(myBaseClass parameter) { parameter.myMethod(); }
- // void myFunction_myDerivedClass(myDerivedClass parameter) { parameter.myMethod(); }
- // Both of which would compile.
- }
- int main()
- {
- myFunction<myBaseClass>(someVariable);
- myFunction<myNonDerivedClass>(someOtherVariable);
- // You might expect this one to fail, because now myNonDerivedClass is not a derived class,
- // But, look at the function it produces:
- // void myFunction_myNonDerivedClass(myNonDerivedClass parameter) { parameter.myMethod(); }
- // It still has a myMethod method, even though this method has no connection to the base class one.
- // This is important for things like operators and such,
- // and means you can write your own classes that work with the STL templated functions,
- // without having to inherit from their classes, as long as you implement the methods it needs
- // to operate.
- }
- int main()
- {
- myFunction<int>(10);
- myFunction<std::vector<std::string>>(someVector);
- // These produce the following functions:
- // void myFunction_int(int parameter) { parameter.myMethod(); }
- // void myFunction_stdstring(std::string parameter) { parameter.myMethod(); }
- // Neither of these compile, because neither has a method named "myMethod".
- }