Skip to content

Instantly share code, notes, and snippets.

@mido3ds
Last active February 25, 2024 17:09
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mido3ds/8ff9e1283a8e1ffdb32b55f1d3e8133a to your computer and use it in GitHub Desktop.
Save mido3ds/8ff9e1283a8e1ffdb32b55f1d3e8133a to your computer and use it in GitHub Desktop.
template inheritance in c++
template<typename T>
class Base
{
public:
T someVariable;
};
#include "Base.hpp"
// the only right way of inheriting template to template
template<typename T>
class Der : public Base<T>
{};
#include "Base.hpp"
// invalid way of inheritence
template<typename T>
class Der<T> : public Base // this line must be `class Der : public Base<T>`
{};
#include "Base.hpp"
// if you want to make specilization of the class, you MUST inherit first then type the specilization
// usual iheritence
template<typename T>
class Der : public Base<T>
{};
// specilization
template<>
class Der<int> : public Base<int>
{};
#include "Base.hpp"
// invalid
class Der : public Base
{};
#include "Base.hpp"
// valid, you are inheriting class to class
class Der : public Base<int>
{};
#include "Base.hpp"
// valid, Der is template class that inherits from Base<int>
template<class T>
class Der : public Base<int>
{};
// invalid, you cant inherit this way
template<typename T>
class Der<T> : public Base<int>
{};
# if you want to run the examples and check them on your terminal
# type make
run_all: *.cpp
g++ -std=c++11 *.cpp -c
clean:
rm *.o

inherit (template to template):

template<typename T>

class Der : public Base<T>

Der is now a template class that iherits from Base

specialize Der

you must inherit it as template first then make the specilzation

template<typename T>

class Der : public Base<T>

...

template<>

class Der<int> : public Base<int>

Der is now a template class and has its own int specilization

inherit (class to template)

template<typename T>

class Der : public Base<int>

inherit (class to class)

class Der : public Base<int>

Der is a class, NOT template class.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment