How should we use a template with std :: accumulate in a function to return the correct type using a non-init template template,

The type of return from std::accumulatedepends on "init", i.e. if it is an integer, it returns an integer, and if it doubles, it will return twice.

I have a template function for an amount like this:

T mean(std::vector<T> vector)
{
    T sum = std::accumulate(vector.begin(), vector.end(), X);
}

What should I put in place of X?

+4
source share
1 answer

You can simply use T{}which is built by default T. eg.

T sum = std::accumulate(vector.begin(), vector.end(), T{});

If you need it to be initialized with some initial value, you can

T sum = std::accumulate(vector.begin(), vector.end(), T{some_initial_value});

or

T sum = std::accumulate(vector.begin(), vector.end(), static_cast<T>(some_initial_value));
+4

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


All Articles