views:

158

answers:

3

Consider the following piece of code:

class B {
  private:
    // some data members
  public:
    friend bool operator==(const B&,const B&);
    friend ostream& operator<<(ostream&,const B&);
    // some other methods
};

template <typename T=B>
class A {
  private:
    // some data members
    vector<vector<T> > vvlist;
  public:
    // some other methods
 };

My requirement is that the type T that is passed as type parameter must provide definitions for the operator== and the operator<< methods. I do not want to enforce any other restrictions on T.

How can I do this?

One way that I can think of is to Create an Abstract class say "Z" that declares these two methods.

and then write

vector<vector<Z> > vvlist;

and NOT have class A as a template.

Is there a better way to do this?

Thanks! Ajay

A: 

You can write a private method in A that would test required stuff on T in compile time.

void TestReq(T x, T y)
{
  if (x==y)
    cout << x;
}

This way even plain integers would pass and work.

Kugel
Not quite. You also have to call this method, otherwise it might just not be compiled. That is, just having this, everything might (would) pass.
UncleBens
+3  A: 

It seems like you are looking for a concept check library. See what Boost has to offer: Boost Concept Check Library. That link also has a good explanation what concepts are. Quote:

A concept is a set of requirements (valid expressions, associated types, semantic invariants, complexity guarantees, etc.) that a type must fulfill to be correctly used as arguments in a call to a generic algorithm

In your question, the concept is "type T must provide operator== and operator<<".

hrnt
+3  A: 

It happens automatically.

If your code calls the operators == and <<, then the code simply won't compile if the class is passed a type that doesn't define these operators.

It is essentially duck-typing. If it looks like a duck, and quacks like a duck, then it is a duck. It doesn't matter whether it implements an IDuck interface, as long as it exposes the functionality you try to use.

jalf