Is there equivalent of <? extends T>, <? super T> in C++?

后端 未结 5 1640
忘了有多久
忘了有多久 2021-02-05 10:33
  1. Is there equivalent of , in C++?

  2. Also, does ,

5条回答
  •  抹茶落季
    2021-02-05 11:31

    You can restrict the range of a template parameter in C++ using the various traits mechanisms, of which there are implementations available in boost.

    Usually you don't - the reason the syntax exists in Java and C# is that they use generics, not templates.

    Java generics generate shared code which uses virtual dispatch from the base type, rather than generating code for each type used as a template argument. So usually you are using the restriction in order to allow you to call methods on objects of the type used as the template parameter.

    As C++ generates code for each type used as a template parameter, it doesn't need to know about a base type for them.

    For example, a template class for a matrix will use +,-,* operators on its target type. In can then be used for any type which supports those operators. If it was arbitrarily restricted to doubles and ints, then you couldn't use the template with a complex or run a test with a type which supports interval arithmetic, even though those types provide those operators, and the matrix library would be valid using them.

    The ability to work on arbitrary types which have the same shape is the power of templates, and makes them more useful. It's up to the client code to decide whether or not it's valid to use that template with that type (as long as it compiles), and the customer is always right. The inability to work on arbitrary types which have the same shape, and the requirement to specify restrictions to call methods other than those of java.lang.Object is a weakness of generics.

提交回复
热议问题