Im new to c++ but not to programming as I've been programming in Java for a while now.
In java one can define a template class like this:
1 2 3 4 5 6
class A<T>
{
....
}
if one wants to make type T as one the extends other class(or implements an interface) :
1 2 3 4 5
class A<T extends someClass>
{
...
}
and now one can use methods of someClass inside of class A because the above decleration guarantee that T "is a" someClass
Can I do it in c++?
I mean if I write
1 2 3 4 5 6 7 8 9 10 11 12 13
template<class T>
class A
{
....
};
How can I guarantee that parametr T is has some other methods/attributes from another class?
Thank u in advance
Eyal
#include <type_traits>
#include <iostream>
struct base { virtual ~base() {} /* ... */ } ;
template < typename T, typename E = void > struct A ;
template < typename T > // implementation for types derived from base
struct A< T, typename std::enable_if< std::is_base_of< base, T >::value, void >::type >
{ staticvoid identify() { std::cout << "T is a derived class of base\n" ; } } ;
// if required
template < typename T > // implementation for types which are not derived from base
struct A< T, typename std::enable_if< !std::is_base_of< base, T >::value, void >::type >
{ staticvoid identify() { std::cout << "T is not derived from base\n" ; } } ;
int main()
{
struct D : base {} ; A<D>::identify() ; // T is a derived classes of base
A<int>::identify() ; // T is not derived from base
}