3 ms·
Let's say you want to write a generic function to convert from a container type to another container type: linked_list<int> l; vector v = to_container(
by gpderetta 5y ago
Let's say you want to write a generic function to convert from a container type to another container type:
linked_list<int> l;
vector v = to_container(l);
In C++ this would be:
template<template<class...> class ResultT, range Range, class T = range_value_t<Range> >
ResultT<T> to_container(Range range) {
return ResultT<T>(begin(range), end(range));
}
list<int> x = ...;
vector y = to_container<vector>(x);
Because of the lack of type inference (only a simple form of type deduction is available in C++)[1], we have to specify the kind of container we want in the call to to_container. We do not have to specify the value type though (int in this case), so the ResultT parameter of to_container is an HKT. Range_value_t is a type query to get the value_type of the range. It is used to initialize a default template parameter purely for syntactical convenience.
This is C++ of course so things are always a bit more complex. In particular a template template parameter is not really a type which makes is harder to manipulate consistently.
More advanced metaprogramming libraries prefer to use types with associated templated types instead, which are another form of HKT, but it is not needed for this case.
There are also ways around having to specify vector in the call to to_container using a proxy result type and a templated conversion operator, but it is again overkill in this case.
Finally note that C++ templates are by default untyped: only instantiations are type checked. We use concepts for the range parameter that at least allows type checking of the range parameter at the call site without full instantiation, but as far as I can tell there are still no higher kinded concepts.
I believe that Rust doesn't have HKTs yet exactly because higher kinded concepts (called traits in rust) are hard to define.
[1] whether languages with proper type inference can deduce HTKs is beyond my pay grade, but I assume they can.
- sargstuff 5y agoProblem isn't "whether languages with proper type inference can deduce HTKs". The issue for rust is in allowing HTKs; can the same rust language guardrails be guaranteed. C++ allows one to get at the underlying "bit patterns" The idea of Rusts gardrails is to prevent that. The more things that sit between the actual "bit patterns", the more ways there are to get at the actual underlying "bit patterns". Programmer defined HTKs add additional paths to the underlying bit patterns which may/maynot include inferences needed for rusts "fixed" guardrails.