Type inference in C++

Last week I was on vacation, and I took the time to relearn C++, as it had been very long since I had last worked seriously with it.

In the process I thought that C++'s template system can also serve as a type inference mechanism.

Because what's the difference between having OCaml guess the types as in this snippet...

# let cat a b = a @ b;;
val cat : 'a list -> 'a list -> 'a list = <fun>
... and having C++ instantiate the template for the appropriate types in this other snippet?
template <typename List>
List cat(const List & a, const List & b) {
  List c = a;
  c.insert(c.end(), b.begin(), b.end());
  return c;
(Modulo syntax errors, of course.)



Answer: the horrible error messages when types don't match. But you already knew that :)

Polimorphist vs Type Inference


There is a difference between type inference and polymorphism. In the caml example, you are not given types at all to the expression, and the compiler "infers" what the type is, the "more exact" translation of the C++ example to camel would have been:

let cat (a: 'a list) (b: 'a list) = (a @ b : 'a list);;

With that, you would have to use polymorphism, without type inference. The c++ example with type inference would have been something like:

var cat(var a, var b) {
var c = a;
c.insert(c.end(), b.begin(), b.end());
return c;

(stealing the "var" syntax from C# something. Basically, to have "type inference" you need implicit typing (i.e. you can declare variables without having to give it any type), the compiler^Wtype checker will find what the correct type is.

Polymorphism is a completely different beast, you have a piece of code that you can use with different types. One typical example is the function that calculates the length of a list. That function is clearly independent of what the is the type of the elements of the list, it just counts them.
Obviously, if you also have type inference, polymorphism becomes more useful, and specially, easier to use. You can just compare the caml example that you wrote, and the caml example that I wrote.

Later, Juan.

Polymorphism vs Type Inference

Obviously, I didn't spell check the subject in the previous comment.

Later, Juan.