我正在尝试使用GCC 4.4.7和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;
}
虽然MSVC2010编译得很好,但GCC 4.4.7给出了以下错误:
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)’
任何想法为何如此以及如何解决这个问题? 使用C ++ 11 lambdas完全重写代码的想法不起作用 - 需要这个代码。
答案 0 :(得分:4)
C ++ 03不允许使用本地类型实例化模板。如果您不能使用C ++ 11或C ++ 14,则可以通过在Aggregate
函数之外移动process
的定义来解决该问题。为了更好地衡量,请将其operator()
设为const
成员。
#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()
{
....
}