Skip to content

Instantly share code, notes, and snippets.

@mido3ds

mido3ds/Base.hpp

Last active May 28, 2017
Embed
What would you like to do?
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
You can’t perform that action at this time.