The type parameters of a function template could be deduced by the compiler from the parameters of the function. For example:
template<typename T>
auto return_value_type_instance(const std::vector<T>&) -> T
{
return T();
}
This is an example of C++11 trailing return type, which return type will be bool
if you pass a std::vector<bool>
instance to the function , char if you pass a char vector, etc:
int main()
{
std::vector<bool> a;
std::vector<char> b;
std::vector<float> c;
bool aa = return_value_type_instance(a);
char bb = return_value_type_instance(b);
float cc = return_value_type_instance(c);
}
Or in a more common example, STL-like algorithms:
template<typename iterator_type>
void print_range(iterator_type begin , iterator_type end)
{
for(iterator_type it = begin ; it != end ; ++it)
std::cout << *it << std::endl;
}
int main()
{
std::vector<int> v = {0,1,2,3};
print_range(v.begin() , v.end());
}
Output:
0
1
2
3