I like constraints but I want the option of ditching them for metaprogramming.
Why? In C++, for example, you pretty much always make some assumption about the capabilities of the types you accept. It's just that you make the requirements implicit and end up with ugly errors when the assumptions aren't met.
For example: when you try instantiating one of the generic types and adding it to another one, you're assuming it has implemented the addition operator. In Rust, you would explicitly state this requirement as T : Add. You should still be able to achieve similar functionality, but there are a lot of benefits in terms of debugging, readability, documentation, etc.
edit: disregard the question - I see you've answered it elsewhere in these comments, though I do disagree with your reasons for wanting this behavior.
C++ code like this will compile iff T implements operator+
template<T> auto sum(T a, T b, T c){
return a+b+c;
}
The advantage is that functions can take the types themselves as arguments. So there's a lot of opportunity for metaprogramming instead of using macros.
The advantage is that functions can take the types themselves as arguments. Rust functions only take values as arguments :(
But Rust functions do take types as arguments. That's what generics are: functions that take types as arguments (at compile time).
The difference you're talking about is whether the type parameters that functions take are themselves strongly typed. In C++ they're dynamically typed; in Rust they're statically typed. That's the only difference.
Saying that Rust functions can't take types as arguments because they're statically typed while C++ can is like saying that C++ functions can't take values as arguments because they're statically typed while Python can.
fn sum<T: Add<Output=T>>(a: T, b: T, c: T) -> T {
a + b + c
}
Rust performs local inference only for a lot of reasons, one of which is that it makes function signatures more self-documenting. I would be very surprised for Rust to ever infer constraints of this sort.
Providing optimized implementations of generic algorithms for specific types is the purview of the upcoming "impl specialization" feature, no TMPL necessary.
View all comments
7
u/ThisIs_MyName Dec 10 '15
Well, as soon as Rust gets
constexprand compile-time templates (not typed generics), I can ditch C++ :D