Created
June 16, 2016 03:34
-
-
Save gxr/066c92792d6f9852fd6e169b53d98f1c to your computer and use it in GitHub Desktop.
Template inheritance with specialization example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
template <typename T> | |
struct Foo { | |
T t; | |
}; | |
template <typename T> | |
class Base { | |
public: | |
typedef Foo<T> Bar; | |
typedef std::vector< Foo<T> > BarVec; | |
virtual BarVec BazVec() = 0; | |
virtual Bar Baz() = 0; | |
}; | |
template <typename T> | |
class Derived : public Base<T> { | |
public: | |
typedef typename Base<T>::Bar Bar; | |
typedef typename Base<T>::BarVec BarVec; | |
//virtual typename Base<T>::Bar Baz(); | |
virtual BarVec BazVec(); | |
virtual Bar Baz(); | |
}; | |
template <> | |
typename Derived<int>::BarVec Derived<int>::BazVec() { | |
Derived<int>::BarVec bvec; | |
Derived<int>::Bar bar; | |
bar.t = 4; | |
bvec.push_back(bar); | |
bvec.push_back(bar); | |
return bvec; | |
} | |
template <> | |
typename Derived<std::string>::BarVec Derived<std::string>::BazVec() { | |
Derived<std::string>::BarVec bvec; | |
Derived<std::string>::Bar bar; | |
bar.t = "abc"; | |
bvec.push_back(bar); | |
bvec.push_back(bar); | |
return bvec; | |
} | |
template <typename T> | |
typename Derived<T>::Bar Derived<T>::Baz() { | |
return BazVec()[0]; | |
} | |
/*template <typename T> | |
typename Derived<T>::Bar Derived<T>::Baz() { | |
return Base<T>::Bar; | |
} | |
template <> | |
typename Derived<int>::Bar Derived<int>::Baz() { | |
Derived<int>::Bar r; | |
r.t = 3; | |
return r; | |
}*/ | |
int main(){ | |
{Derived<int> d; | |
//Foo<int> gg = d.Baz(); | |
Foo<int> gg = d.Baz(); | |
std::cout << gg.t << std::endl;} | |
{ | |
Derived<std::string> d; | |
//Foo<int> gg = d.Baz(); | |
Foo<std::string> gg = d.Baz(); | |
std::cout << gg.t << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment