2

In Java generics, we can simply use MyClass<T implements SomeInterface>. However, I couldn't think of a C++ equivalent for this.

Then, when I have a template class T, how do I specify what particular methods this T supports?

OneZero
  • 11,556
  • 15
  • 55
  • 92

1 Answers1

2

Concepts is what you are looking for. However, they are not in current C++ standard yet. So what you can do about this is to use SFINAE

A type trait to determine if some type respect some kind of interface could be made with many type trait that are looking for a certain member.

This is what a type trait for to determine if a class has a specific member look like this:

template<typename T>
struct has_member1 {
private:
    template<typename C> static std::true_type test(decltype(C::THE_MEMBER_NAME)*);
    template<typename C> static std::false_type test(...);

public:
    constexpr static bool value = decltype(test<T>(nullptr))::value;
};

So by now you can already check for a specific member. To check for an interface, you can do something like this:

template<typename T>
struct is_my_interface {
    constexpr static bool value = 
        has_member1<T>::value &&
        has_member2<T>::value &&
        has_member3<T>::value;
};

And now your template class:

// declare it
template<typename, typename = void> struct MyClass;


template<typename T>
struct MyClass<T, enable_if_t<is_my_interface<T>>> {
    // class body
};
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141
  • 1
    C++11 also added support for [`std::is_base_of`](http://en.cppreference.com/w/cpp/types/is_base_of). – Jason Oct 27 '15 at 18:53