简体   繁体   中英

c++ stl functions template type deduction

I've been looking around in, and coding some basic examples for std::algorithm and for some reason i never found it odd that they work like this for example:

#include <vector>
#include <algorithm>
int main(){
  std::vector<int> vec;
  vec.resize( 100 );

  std::generate( std::begin( vec ), std::end( vec ), std::rand );   
  auto element = std::max_element( std::begin( vec ), std::end( vec ) );
}

How come it does not require template parameters like this:

std::generate<std::vector<int>::iterator>( ... 
std::max_element<std::vector<int>::iterator>( ...

Look at std::generate possible implementation:

template<class ForwardIt, class Generator>
void generate(ForwardIt first, ForwardIt last, Generator g)
{
    while (first != last) {
        *first++ = g();
    }
}

Here ForwardIt type is deduced by the compiler from first and last parameters.

Then, both std::begin and std::end functions return iterators for the container. These are std::vector iterators in your case.

Consequently, ForwardIt is deduced as a type of std::vector iterator and you do not have to specify it explicitly.

The same logic applies to other algorithms.

std::begin and std::end return iterators so you don't need to tell it explicitly to the compiler. Also as you are passing the vector as a parameter to those two functions, the compiler will know the template parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM