문제

While going through the book "Effective STL" the author gives an example of how a copy_ifcould be written since this does not exist in the standard algorithms. Here is the authors version:

template <typename Input, typename Output,typename Predicate>
OutputIterator copy_if(Input begin , Input end, Output destBegin, Predicate p)
{
   while(begin != end)
   {
     if(p(*begin)) *destBegin++=*begin;
     ++ begin;
   }
   return destBegin; 
}

Now my question is how can the author use that method like this:

copy_if(widg.begin(),widg.end(),ostream_iterator<widg>(cerr,"\n"),isDefective);

My question is why isnt the template parameters being defined with copy_if (since it requires 3) such as this

copy_if<p1,p2,p3>(...)
도움이 되었습니까?

해결책

For function templates such as copy_if, the compiler can deduce the types of the template parameters from the function parameters. You don't have to supply them yourself, although I don't think it's an error if you do.

This is different from class templates where you do have to explicitly supply the template parameters.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top