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++?
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.
No; there is no language feature to do this.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With