【问题标题】:Are there boost::bind issues with VS2010?VS2010 是否存在 boost::bind 问题?
【发布时间】:2010-11-22 17:35:47
【问题描述】:

我有以下代码行,在 2010 年之前在 g++ 和 Visual Studio 下编译得很好。

std::vector<Device> device_list;

boost::function<void (Device&, boost::posix_time::time_duration&)> callback = 
  boost::bind(&std::vector<Device>::push_back, &device_list, _1);

Device 是一个类,没什么特别的。

现在我刚刚将我的 Visual Studio 版本升级到 2010,编译失败:

Error   1   error C2780: 'boost::_bi::bind_t<_bi::dm_result<MT::* ,A1>::type,boost::_mfi::dm<M,T>,_bi::list_av_1<A1>::type> boost::bind(M T::* ,A1)' : expects 2 arguments - 3 provided C:\developments\libsystools\trunk\src\upnp_control_point.cpp    95

发生了什么,我该如何解决?

谢谢。

【问题讨论】:

    标签: c++ visual-studio-2010 boost bind


    【解决方案1】:

    这可能是因为 vector::push_back 现在通过支持或 C++0x 特性有 2 个重载,使得 bind 模棱两可。

    void push_back(
       const Type&_Val
    );
    void push_back(
       Type&&_Val
    );
    

    这应该可以工作,或者使用@DeadMG 的回答中建议的内置函数:

    std::vector<Device> device_list;
    
    boost::function<void (Device&, boost::posix_time::time_duration&)> callback = 
      boost::bind(static_cast<void (std::vector<Device>::*)( const Device& )>
      (&std::vector<Device>::push_back), &device_list, _1);
    

    【讨论】:

    • +1。感谢您的解释和解决方案。我永远不会想到静态转换函数指针;)
    【解决方案2】:

    MSVC10 中存在绑定问题。这不是我第一次看到报告问题的帖子。其次,由于引入了 lambda,它完全完全多余,并且 boost::function 已被 std::function 取代。

    std::vector<Device> devices;
    std::function<void (Device&, boost::posix_time::time_duration&)> callback = [&](Device& dev, boost::posix_time::time_duration& time) {
        devices.push_back(dev);
    };
    

    在 MSVC10 中无需使用绑定。

    【讨论】:

    • btw boost::bind 具有模棱两可的成员函数重载不仅在 Visual C++ 中存在问题,而且 +1 用于优雅的替代方案
    • 有很多理由在 C++0x 中使用绑定。
    • @Noah:你的意思是你更喜欢绑定语法而不是 lambdas 还是你在谈论技术方面(性能?)?
    • @Noah:当你发布它时我会相信它。 @Matthieu:从内存中,lambdas 在通过引用传递时实际上非常快 - 比使用函数对象更快,因为编译器可以通过传递堆栈指针并为所有变量从它偏移来实现它们,从而使 lambda 更小并且更高效。
    • +1。感谢您提供有趣的解决方案。不幸的是,我不能使用一些新的 C++0x 特性,因为我必须让我的代码与不提供这些特性的其他编译器兼容。
    猜你喜欢
    • 2012-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-05-26
    • 2012-04-18
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多