Pierpaolo Vesce
Pierpaolo Vesce

Reputation: 131

Template sum of container elements (problems with value_type returned)

this is an exercise from a previous c++ test I took:

Implement a template function sum which takes in a numbers container and returns their sum. (Tip: if C it's the container type, the elements type is returned, for example, from C::value_type).

At the time of the test I wasn't prepared at all, but now, for a sum of a generic container I'd go like that:

template<typename Iter>
double sum(Iter b, Iter e)
{
    double ret=0;
    for(;b!=e;b++)
        ret+=*b;
    return ret;
}

or

template<typename C>
double sum(const C& cnt)
{
    double ret=0;
    for(auto it=cnt.begin();it!=cnt.end();it++)
        ret+=*it;
    return ret;
}

My question here is how can I replace the function return argument with the actual container elements type?

Upvotes: 0

Views: 225

Answers (1)

rafix07
rafix07

Reputation: 20934

Use typename C::value_type:

template<typename C>
typename C::value_type sum(const C& cnt)
{
    typename C::value_type ret{}; // default initialization
    for(auto it=cnt.begin();it!=cnt.end();it++)
        ret+=*it;
    return ret;
}

Since C++14 you can use auto as return type of sum template:

template<typename C>
auto sum2(const C& cnt) // before calling check if cnt is not empty
{
    auto it = cnt.begin();
    auto ret = *it;   // deduce type by dereferencing
    for(++it;it!=cnt.end();it++)
        ret+=*it;
    return ret;
}

Upvotes: 2

Related Questions