3 ms·
> C++'s templates can't do that. In C++ even if the types look generic, your code can make assumptions about the types. If you want an assertion that a class p
by josefx 5y ago
> C++'s templates can't do that. In C++ even if the types look generic, your code can make assumptions about the types.
If you want an assertion that a class pretends to implement certain semantics (a.k.a. implements an interface) then you can have a specialized struct that has to be declared for every class used with your template. Either the user provides it and guarantees that their identity() function implements the required semantics of identity() or he doesn't and the code fails to compile. You could also check explicitly if the template parameter type inherits from a certain interface type, but that tends to exclude a lot of types that do not generally implement any interface explicitly, cant remember an IIdentityProviderFactoryBuilderManagementJavaJXBeanObserverInterface on int for example.
- eru 5y agoGoing via the interface route that you described doesn't rescue C++ here. The thing that parametric polymorphism gives you is that the type system can ensure that your code is not doing anything with your values but pass them around. And you don't need to read nor trust any implementation code for that. For what you describe you could still implement cosine for float, and 'not' for bools, and identity for char. We don't want the class to implement certain semantics. We'd want an assurance that certain semantics are _not_ implemented (in some sense). We want an assurance that the code is forced to treat the value as an opaque black box.