Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Enforcing template type implements a method

I have a template class and I want to know if it is possible to enforce that the template class type implements a certain interface, in particular I want to enforce that the type overloads the operator= method. In Java I would write:

public class Tree<T implements IComparable>{
    public Tree(Vector<T> x){...}
}

What is the alternative in C++?

like image 459
Aly Avatar asked Feb 19 '23 19:02

Aly


2 Answers

Just write the code assuming that it does. If it doesn't, it will fail to compile when the user passes in the non-conforming type. There is no need for an explicit feature here. But why on earth would you ever need an interface like IComparable for this? Templates are duck typed.

But the template error might get nasty. You can use type traits and static assert to make this simpler. However, the Standard doesn't provide a trait like this, so you'd have to write one with SFINAE.

like image 165
Puppy Avatar answered Feb 27 '23 17:02

Puppy


Short answer:

No; there is no language feature to do this.

Shotish Answer:

The affect you want can be achieved using SFINAE and static asserts (asserts that are evaluated at compile time). Unfortunately this is a non trivial processes and requires a good understanding of template meta programming.

Longish Answer:

The features was suggested for the new C++11 standard, but did not make it through the review process. Read more here http://en.wikipedia.org/wiki/Concepts_(C%2B%2B) . At the current meeting (Portland Oct/12-19) Herb Sutter was suggesting that we should try for a two phase release (a minor followed by a new feature release) and concepts would be included in the first minor release. Whether this proposal is accepted will be available after the meeting.

like image 28
toucan Avatar answered Feb 27 '23 16:02

toucan