Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GCC cannot resolve proper std::accumulate

I'm trying to compile code like this using both GCC 4.4.7 and MSVC 2010:

// test.cpp
// use g++ -c test.cpp to attempt compile this 

#include <map>
#include <numeric>
#include <algorithm>

struct A
{
        A() : v1(0), v2(0) {}
    int v1, v2;
};

typedef std::map<int, A> A_map;

void fill_map(A_map& m); // external function

A process()
{
        A_map m;
        fill_map(m);
        A a;
        if(!m.empty())
        {
                struct Aggregate
                {
                        A operator()(const A& left, const A_map::value_type& right)
                        {
                                A result;
                                result.v1 = left.v1 + right.second.v1;
                                result.v2 = std::max(left.v2, right.second.v2);
                                return result;
                        }
                };
                A a0;
                a = std::accumulate(m.begin(), m.end(), a0, Aggregate());
        }
        return a;
}

While MSVC2010 compiles this nicely, GCC 4.4.7 gives following error:

test.cpp: In function ‘A process()’:
test.cpp:33: error: no matching function for call to ‘accumulate(std::_Rb_tree_iterator<std::pair<const int, A> >, std::_Rb_tree_iterator<std::pair<const int, A> >, A&, process()::Aggregate)’

Any ideas why so and how to fix this? Ideas like completely rewrite code using C++11 lambdas do not work - need exactly this code.

like image 445
ivan.ukr Avatar asked Jun 19 '26 03:06

ivan.ukr


1 Answers

C++03 does not allow for the instantiation of templates with local types. If you can't use C++11 or C++14, you can fix that problem by moving the definition of Aggregate outside of the process function. For good measure, make its operator() a const member.

#include <map>
#include <numeric>
#include <algorithm>

struct A
{
    A() : v1(0), v2(0) {}
    int v1, v2;
};

struct Aggregate
{
  A operator()(const A& left, const A_map::value_type& right) const
  {
    ....
  }
};

void fill_map(A_map& m); // external function

A process()
{
  ....
}
like image 108
juanchopanza Avatar answered Jun 21 '26 17:06

juanchopanza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!