template class like Java

Hi all,

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 
> Can I do it in c++?

SFINAE is the primary C++ mechanism for compile-time reflection.
http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#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 >
{ static void 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 >
{ static void 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
}


http://en.cppreference.com/w/cpp/types/is_base_of
http://en.cppreference.com/w/cpp/types/enable_if
Topic archived. No new replies allowed.