5 ms·
The problems you mentioned about type inference are valid, but this issue lies is any programming language which provides this feature, and a lot of languages w
by teitoklien 5y ago
The problems you mentioned about type inference are valid, but this issue lies is any programming language which provides this feature, and a lot of languages which are promoted and looked upto on HN (like Haskell) heavily use type inference.
The simplest answer to your question of how to know what type the compiler will choose for type inferenced variables, is by compiling an example code snippet and printing out the type using either something like decltype or typeid (preferably the former).
But the thing is, the point of type inference is you want to abstract away the type, if you want to explicitly be aware of the type at all times, you should explicitly state it in declarations.
The issues described is inherent in the very notion of letting the compiler infer the type for you, which leads to this ambiguity.
If you want to avoid it, then best to be explicit, if you dont care about the type and are using typeinference to build compile time simple template functions using lambda and the type inferred parameters.
Then type inference is pretty handy and leads to easy to read code.
It’s a tool, when you feel it’s getting in your way at writing code, you remove the tool/feature from your code.
- tsimionescu 5y ago> but this issue lies is any programming language which provides this feature, and a lot of languages which are promoted and looked upto on HN (like Haskell) heavily use type inference. > The issues described is inherent in the very notion of letting the compiler infer the type for you, which leads to this ambiguity. It's not the same thing. Types and type qualifiers are different things, and few languages have type qualifiers in the same way as C++. In fact, auto, unlike type inference in any other language, does NOT match the full type of the variable - that's why things like `volatile auto &x = y` exist. > But the thing is, the point of type inference is you want to abstract away the type That's the point in other languages. In C++ it's much more just shorthand for the horribly long type names you end up with in templates.
- gpderetta 5y agoAuto (and type deduction in general) is important in generic code.
- tsimionescu 5y agoC++ had generic code for many years before auto (and decltype) existed. It definitely makes things easier, and I believe there are some types today that work with auto but can't be named otherwise. But, it's not directly required outside of these. Template parameter inference, which mostly uses the same rules, is probably required in some SFINAE constructs, but is also not essential in other places.