Reputation: 11238
When creating a function template in C++, is it possible to specify something like a generic constraint in C# on a type parameter? For instance this function template makes sense only for types that define <
and ==
(in C# the signature would be int Compare<T>(T item1, T item2) where T : IComparable<T>
):
template <typename T>
int compare(const T &item1, const T &item2)
{
if (item1 == item2) return 0;
if (item1 < item2) return -1;
if (item2 < item1) return 1;
}
Upvotes: 2
Views: 95
Reputation: 55897
It's possible by using boost, but not possible in current standard. There will be concepts lite (in feature) (read this for more information). Now you can only write your own library, use std::enable_if
or something else, or use boost concept check library.
Upvotes: 2
Reputation: 477710
Yes, that's possible, but it's not necessarily desirable or required.
If your types don't provide the required operators, you'll get a compile-time error anyway, saying something to the effect that you can't apply the operator to those types. So there's no outright danger in having an unconstrained template.
It is possible, using metaprogramming techniques such as SFINAE, to remove the template from the overload set entirely unless the types meet the constraints, so that the template definition will never even be considered, but that will potentially lead to a weirder situation and error message. It is sometimes desirable or necessary to remove overloads from consideration (usually for constructors), but this doesn't appear to be such a case. Moreover, the techniques for doing this are a bit verbose and ad-hoc.
A future version of C++ may try and solve this via concepts, but that is not a mature technology yet.
Upvotes: 2
Reputation: 25663
Have a look for SFINAE in general.
in c++11 there are a lot of helping functionality arround SFINAE like enable_if and a lot of type traits. And yes, you can also check for the existence of a member function of a given type.
The trick in general is, that a template declaration while fail but give no error if the failure arises before the definition block.
Upvotes: 0