Template Deduction for C++

Template is a confusing and hard features in C++ if you want use it well, and I think it is also one of the reason which causes c++ programmers cannot understand each other. Sometimes the Deduction rule for c++ is really confusing, you don’t understand why you code doesn’t work or why it works. And Since STL heavily uses nesting Templates, both your compiler and your mind suffers from that.

##Function Templates People commonly start define and using templates for Container, such as std::vector and std::map. Soon later, they want to write template functions instead of overloading. The sort function from standard library is a good example. It is usually defined as:

template<class RandomIt> void sort(RandomIt& first, RandomIt& last).

Then you can sort a vector by:

std::vector<float> a = ...;
std::sort(a.begin(), a.end())

The compilers try to infer the template parameters from template functions' parameters. Sometimes compilers are not smart enough to deduce it out, then you have to specific it yourself. The deducing mechanism is a choice of compilers. For example, compilers never tries to deduce the type for a class template. Compilers deduction policy is hard to implement, and quite often, I blame for compiler’s stupidity for not be able to deducing the templates(but of course, the guys that wrote compiler usually smart than us). But for us, we need to know when we don’t need to specific the template parameters, when we will need to. According to CPP Reference, the difference is there are some context participate into deduction, others does not.

  • Template deduction for template functions can be done with function arguments.
  • Compiler never deduce templates for class.
  • Template deduction cannot be done with return types.
  • Nested types such as std::vector<std::complex<double> > can causes troubles.
  • A template type that uses another template, like F& (*function)(T l, T r), here F is not deductible.
  • And there are many other rules.

Looks like now, the deduction can only be done with direct type that list in code.

comments powered by Disqus