3 ms·
Can anyone ELI5 the difference between dependent types and what Rust calls const generics and what C++ calls non-type template parameters? If I have a type that
by dataangel 5y ago
Can anyone ELI5 the difference between dependent types and what Rust calls const generics and what C++ calls non-type template parameters? If I have a type that is templates/generic on an integer value, e.g. ‘MyType<3>’ is that a dependent type?
- codebje 5y agoA dependent type is a function from a value to a type - where a value is a runtime value, not a compile time constant. Can you do 'MyType<n> foo(int n) {...}' ?
- drdeca 5y agoIf that 3 can be decided at runtime rather than at compile time, yes. Like, if I can have a type Array<Type,Length> and have a function f which has as its input type Int, with the name of the input variable being n, and as its return type Array<Bool,n> and when you give the return value to something else, it checks (at compile time) that the length of the array (i.e. , n ) matches what the other thing is expecting, that would be using dependent types.
- steveklabnik 5y agoThey're subsets of true dependent types, in my understanding. This is because they can only do this at compile time, not runtime. There's no way to say, get a number over stdin, put it in a variable n, and then instantiate MyType<n> with that variable. You can with true dependent types.
- stkdump 5y agoYou could do this with the factory pattern, applied to a template type. Though, if you would do this for the whole range of say, an int, you would probably blow up the compiler. How is that done in languages that do support this? Or does it require shipping the compiler, so that you can run the compiler at runtime?
- steveklabnik 5y ago> You could do this with the factory pattern, applied to a template type. I don't know enough about C++ templates here, but you cannot in Rust. > How is that done in languages that do support this? I don't know enough about the implementations to actually say, to be honest. Most of them aren't systems languages, and so have significantly less constraints on implementations, and less monomorphization. I imagine that helps.