c++ - 为什么 bind1st 和 bind2nd 需要常量函数对象?

标签 c++ templates stl

所以,我正在编写一个 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 来工作(它只对第二个参数 xtypename Operation::second_argument_type(x) 等起作用)。

关于c++ - 为什么 bind1st 和 bind2nd 需要常量函数对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2796233/

相关文章:

c++ - c++17 中的非类型模板参数可以是 decltype(auto) 吗?

C++ 迭代器到 const_iterator

c++ - 检查当前元素是否是集合的最后一个元素

c++ - std::abs 与 std::transform 不工作

c++ - 当同名类模板存在时,需要范围解析运算符调用成员函数模板

c++ - 隐式类实例化翻译单元 : multiple definition when linking

c++ - 如何直接访问类的私有(private)成员?

html - 帮助在页面中定位 Flash 文件

c++ - clEnqueueCopyBufferRect 是如何工作的?

c++ - 使用循环停止 QThread 的正确方法(从 opencv 读取视频)