【问题标题】:Boost bind and 'result_type': is not a member, c++03-friendlyBoost bind 和 'result_type': 不是成员,对 c++03 友好
【发布时间】:2020-06-05 11:02:13
【问题描述】:

Visual Studio 2019 的最新 16.6 更新删除了 std::plus::result_typestd::minus::result_type 和相关的 typedef。 (它们在 C++17 中被弃用,在 C++20 中被删除。)代码的一个大大简化的版本如下所示:

template <typename FF>
struct function_wrapper {
    function_wrapper(FF func, const std::string& name) : func_(func), name_(name) { }
    int operator()(int i1, int i2) const { return func_(i1, i2); }
    // ... other stuff ...
    FF func_;
    std::string name_;
};

template <typename FF>
int use_function(const function_wrapper<FF>& func, const std::pair<int, int>& args) {
    return func(args.first, args.second);
}

funcWrapper<boost::function<int(int, int)>> plus_func(std::plus<int>(), "plus");
std::cout << use_function(plus_func, std::make_pair<int, int>(1, 2)) << std::endl;

更新后,这不再编译,产生错误:

boost\1.72.0\boost\bind\bind.hpp(75,25): error C2039: 'result_type': is not a member of 'std::plus<int>'

我无法将result_type typedef 添加回std::plus,因此我需要另一种方法来解决此问题。问题是,生成的代码也需要在 C++03 下编译,因此 lambdas 和 >=C++11 构造不是一个可行的选择。我可以重新实现 std::plus 并自己添加现在已删除的 typedef 以使 Boost 满意,但有更好的方法吗?

【问题讨论】:

  • 注意:std::make_pair 应该在没有显式模板参数的情况下被调用,即std::make_pair(1, 2)

标签: c++ visual-studio-2019 c++03 c++20 boost-bind


【解决方案1】:

用:

包装旧的函子
template <typename F>
struct functor;

template <template <typename> class F, typename T>
struct functor<F<T> > : F<T>
{
    typedef T result_type;
    typedef T first_argument_type;
    typedef T second_argument_type;
};

然后:

function_wrapper<boost::function<int(int, int)> >
     plus_func(functor<std::plus<int> >(), "plus");
//             ~~~~~~~^              ~^~

或者,您可以调用boost::bind,将结果类型指定为模板参数:

boost::bind<int>(func, args...);

或:

boost::bind(boost::type<int>(), func, args...);

【讨论】:

    猜你喜欢
    • 2019-03-23
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 2011-03-04
    相关资源
    最近更新 更多