Re:Python type hints may not be not for me in practice
by maleldil on Thursday November 28, 2024 @06:00AM
(#42264335)
C++ has extensive type inference now (C++20):
#include <string>
auto func(auto x, auto y) -> auto {
return x + y;
}
auto main() -> int {
auto i = func(1, 2);
auto s = func(std::string("a"), std::string("b"));
}
`int` is required as a return type from `main`, but everything else is inferred. This works because `func` becomes a template function where each parameter type is a separate template type, so you get compile-time duck typing. It also works with concepts (e.g. `std::integral auto x`).It's quite neat, but I don't think anyone actually writes code this way, except for lambdas.
We’ve come a long way from the C++ or Java I wrote when I was young, where types were named and renamed constantly. As I understand it, even C++ has the auto keyword now.