所以,我正在编写一个 C++ 程序,它可以让我控制整个世界。我已经完成了最终翻译单元的编写,但出现错误:
error C3848: expression having type 'const `anonymous-namespace'::ElementAccumulator<T,BinaryFunction>' would lose some const-volatile qualifiers in order to call 'void `anonymous-namespace'::ElementAccumulator<T,BinaryFunction>::operator ()(const point::Point &,const int &)'
with
[
T=SideCounter,
BinaryFunction=std::plus<int>
]
c:\program files (x86)\microsoft visual studio 9.0\vc\include\functional(324) : while compiling class template member function 'void std::binder2nd<_Fn2>::operator ()(point::Point &) const'
with
[
_Fn2=`anonymous-namespace'::ElementAccumulator<SideCounter,std::plus<int>>
]
c:\users\****\documents\visual studio 2008\projects\TAKE_OVER_THE_WORLD\grid_divider.cpp(361) : see reference to class template instantiation 'std::binder2nd<_Fn2>' being compiled
with
[
_Fn2=`anonymous-namespace'::ElementAccumulator<SideCounter,std::plus<int>>
]
我查看了 binder2nd
的规范,发现它是:它采用了一个 const
AdaptibleBinaryFunction。
所以,没什么大不了的,我想。我只是用 boost::bind
代替,对吗?
错了!现在我的 take-over-the-world 程序编译时间太长(bind
用于实例化很多的模板中)!照这样下去,我的死对头要先称霸天下了!我不能让这种情况发生——他使用 Java!
那么有人能告诉我为什么做出这个设计决定吗?这似乎是一个奇怪的决定。我想我现在必须让我的类的一些元素可变
......
编辑:有问题的代码:
template <typename T, typename BinaryFunction>
class ElementAccumulator
: public binary_function<typename T::key_type, typename T::mapped_type, void>
{
public:
typedef T MapType;
typedef typename T::key_type KeyType;
typedef typename T::mapped_type MappedType;
typedef BinaryFunction Func;
ElementAccumulator(MapType& Map, Func f) : map_(Map), f_(f) {}
void operator()(const KeyType& k, const MappedType& v)
{
MappedType& val = map_[k];
val = f_(val, v);
}
private:
MapType& map_;
Func f_;
};
void myFunc(int n)
{
typedef boost::unordered_map<Point, int, Point::PointHash> Counter;
Counter side_count;
ElementAccumulator<SideCounter, plus<int> > acc(side_count, plus<int>());
vector<Point> pts = getPts();
for_each(pts.begin(), pts.end(), bind2nd(acc, n));
}
最佳答案
binder2nd
构造函数采用 引用 到 AdaptableBinaryFunction
-- 不是 const
AdaptableBinaryFunction
本身。你的实例化代码怎么样?通常不会明确提及 binder2nd
而是通过便利函数 bind2nd 来工作(它只对第二个参数 x
和 typename Operation::second_argument_type(x)
等起作用)。
关于c++ - 为什么 bind1st 和 bind2nd 需要常量函数对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2796233/