4 ms·
It makes no sense in Python as it's a static typing feature. It makes limited sense for C++ as its generics are structural rather than nominative, though I beli
by masklinn 9y ago
It makes no sense in Python as it's a static typing feature. It makes limited sense for C++ as its generics are structural rather than nominative, though I believe Concepts will (eventually) introduce constrained templates: http://en.cppreference.com/w/cpp/language/constraints http://en.cppreference.com/w/cpp/language/constraints [0]
It does already exists in other languages e.g. Haskell or Rust. For instance in Rust Vec's implementation of Eq is defined thus:
impl Eq for Vec<T> where T: Eq {}
So Eq is implemented on Vec<T> if and only if T implements Eq.
Haskell is similar:
instance (Eq a) => Eq [a] where (…)
the bit before the "=>" is the constraint.
[0] in current C++, you'd just define an `==` operator on your type, and it would blow up with obscure errors if you tried applying it incorrectly e.g. vector already overrides operator==, if you use it with a type which does not override == you get a few pages of templates garbage (287 lines in g++) boiling down to "==(vector<T>, vector<U>)" requires ==(T, U) but I couldn't find that definition. You can try it live with this (requires C++11):
#include <iostream>
#include <vector>
struct S {
uint8_t a;
//bool operator==(const S& other) const {
// return this->a == other.a;
//}
};
int main() {
std::vector<struct S> v1 = { { 3 } };
std::vector<struct S> v2 = { { 4 } };
bool r = v1 == v2;
std::cout << r << std::endl;
}
uncomment the operator== definition and it'll compile.