by ncmncm · 7y ago · 0 comments
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?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. #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;
} 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`.