C ++ templates with multiple constraints
In C #, I use to specify multiple constraints on a generic method or type, as shown here:
How do I specify multiple generic type constraints for a single method?
I started with C ++ for the first time today and I can't seem to find anything useful when googling for multiple template constraints.
It looks like this is impossible, and everyone knows it, and therefore no questions are asked.
I know that generics in C # are much stronger compiler-validated than in C ++ and that is why I feel bad that I cannot constrain my types to multiply supertypes.
source to share
you usually make constraints on the C ++ template with std::enable_if
here is the trick - if your template looks like this:
template <class T>
<return type> <function name> (args...)
you take the return type and combine it with enable_if
this:
template <class T>
typename std::enable_if<XXX,<return type>>::type
<function name> (args...)
here XXX
represents your compile time condition.
eg: let it add(T1 t1 , T2 t2)
be compiled only for objects that inherit from Addable
:
template <class T1, class T2>
typename std::enable_if<
std::is_base_of<Addable,T1>::value && std::is_base_of<Addable,T2>::value
decltype(T1()+T2())>::type
add (T1 t1, T2 t2){
return t1+t2;
}
source to share
This is possible in C ++ today, but with a rather complex syntax. In the next release of C ++, we will most likely get a version of concepts that will make this much easier.
In C ++ 14, the above C # example looks like this:
template <class TResponse, class TRequest,
std::enable_if_t<std::is_base_of<MyClass, TRequest>::value &&
std::is_base_of<MyOtherClass, TResponse>::value>* = nullptr>
TResponse Call(TRequest request);
source to share