In C ++, how can I use the template function as the third parameter in std :: for_each?

I am trying to use std :: for_each to output the contents of vectors that may contain different types. Therefore, I wrote a general output function as follows:

template<typename T> void output(const T& val)
{
    cout << val << endl;
}

which I would like to use with:

std::for_each(vec_out.begin(), vec_out.end(), output);

but the compiler complains about "failed to print the template argument" in the for_each statement. Also complains about "function template cannot be an argument for another function template".

Is it impossible? I would think that the compiler would know the type vec_out (it is a vector) and therefore should create an instance of the function "output (const double & val)"?

If this does not work, how can I get similar STL functions without writing manual loops?

I am new to C ++ and still learning the ropes :-)

+3
3

Try:

std::for_each(vec_out.begin(), vec_out.end(), output<T>);

vec_out - (vector) T.

. for_each . . .

+9

. - output<int>, .

:

template<typename T> void output(const T& val)
{
    cout << val << endl;
}



void main(int argc,char *argv[])
{
    std::vector<int> vec_out;
    std::for_each(vec_out.begin(), vec_out.end(), output<int>);
}   
+7

I just wanted to add the correct answers: the compiler can infer this type if you end your template function in a function object (also like a functor):

struct OutputFunctor
{
  template <typename T>
  void operator()(const T& val) const { output(val); }
};

void test()
{
  std::vector<int> ints;
  std::vector<float> floats;

  std::for_each(ints.begin(), ints.end(), OutputFunctor());
  std::for_each(floats.begin(), floats.end(), OutputFunctor());
}
+7
source

Source: https://habr.com/ru/post/1706875/


All Articles