4

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++?

4

2 に答える 2

5

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.

于 2012-10-17T11:56:59.370 に答える
3

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.

于 2012-10-17T11:53:16.810 に答える