Mad*_*ter 5 c++ boost-bind c++03 c++20 visual-studio-2019
Visual Studio 2019 的最新 16.6 更新删除了std::plus::result_type、std::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;
Run Code Online (Sandbox Code Playgroud)
更新后,不再编译,生成错误:
boost\1.72.0\boost\bind\bind.hpp(75,25): error C2039: 'result_type': is not a member of 'std::plus<int>'
Run Code Online (Sandbox Code Playgroud)
我无法将result_typetypedef 添加回std::plus,因此我需要另一种方法来解决此问题。问题是,生成的代码也需要在 C++03 下编译,因此 lambda 和 >=C++11 构造不是一个可行的选择。我可以自己重新实现std::plus并添加现在已删除的 typedef,以使 Boost 满意,但是有更好的方法吗?
将旧函子包装为:
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;
};
Run Code Online (Sandbox Code Playgroud)
然后:
function_wrapper<boost::function<int(int, int)> >
plus_func(functor<std::plus<int> >(), "plus");
// ~~~~~~~^ ~^~
Run Code Online (Sandbox Code Playgroud)
或者,您可以调用boost::bind指定结果类型作为模板参数:
boost::bind<int>(func, args...);
Run Code Online (Sandbox Code Playgroud)
或者:
boost::bind(boost::type<int>(), func, args...);
Run Code Online (Sandbox Code Playgroud)