3 ms·
Am I confused, or is Wesley? C++ supports dependent types: template<typename T> T add(T, T); C++ doesn't have borrow checking. Maybe he means no non-obli
by ncmncm 8y ago
Am I confused, or is Wesley?
C++ supports dependent types:
template<typename T>
T add(T, T);
C++ doesn't have borrow checking. Maybe he means no non-obligate-GC language has dependent types and borrow checking?
- net4all 8y agoIn the example the return type of add does not depend on the value of the arguments. So it is not dependent types.
- Davidbrcz 8y agoIn this piece of code, the return type is explicitly dependent of the type of the argument (it's path related template #include <iostream> #include <string> struct A {using ret = std::string;}; struct B {using ret = int;}; template <class T> auto f(T t) -> typename T::ret { return {}; } int main(int argc, char *argv[]) { auto s = f(A{}); std::cout << s.size() << "\n"; auto i = f(B{}); std::cout << i+1 << "\n"; return 0; } There is also stuff like this where the return type is defined as the return type of builder.makeObject(), builder which is the argument: template <typename Builder> auto makeAndProcessObject (const Builder& builder) -> decltype(builder.makeObject() ) { auto val = builder.makeObject(); // do stuff with val return val; }
- Retra 8y agoThe return type has to be dependent on the value of the input, not its type. Like it'll return an int[3] if you provide 3 as in input and int[4] if you provide 4. Note that both 3 and 4 should have the same type, but int[3] and int[4] are different types.
- TheAsprngHacker 8y agoAs net4all pointed out, your C++ example isn't really dependent types. It's achievable with parametric polymorphism a la System F, AKA the ML-style or Java-style generics. C++ does have value arguments for templates, however. Perhaps a better example would have been std::array, which takes a size as an argument. However, C++ still doesn't really have dependent types the same way Agda or Idris has them. One big difference is that C++ templates are only checked upon instantiation. So, this code: template<typename T, T a> std::array<int, a + 1> add() { return {1, 2}; } compiles, but when I try to do add<int, 0>() the compiler complains. Because the dependent function type means "forall," it's important that the compiler make sure that it truly does work for all inputs.
- pjmlp 8y agoAs of ISO C++20 that is no longer true, if the template makes use of concepts.
- KayEss 8y agoI think the closest you can get is something like: class odd {...}; class even {...}; std::variant<odd, even> p(int a) { if (a&1) return odd{a}; else return even{a}; } Now which of `even` or `odd` you get is based on the value of `a`.
- gpderetta 8y agoC++ templates can be parameterized by constants, but not runtime values.