1

我正在尝试将构造自的类型对列表传递boost::mp11::mp_product给一个函数,该函数将这些对与一个附加函数参数通过boost::mp11::mp_for_each.

我找到的文档mp_for_each仅限于与通用 lambda 或纯函数一起使用,所以我似乎无法弄清楚使用 是否std::bind是要走的路;如果是,我做错了什么会产生以下编译器错误:

error: no matching function for call to 'bind'
                           std::bind(inject_foo, m, std::placeholders::_1));
                           ^~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/functional:2953:1: note: candidate template ignored: couldn't infer template argument '_Fp'
bind(_Fp&& __f, _BoundArgs&&... __bound_args)
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/functional:2962:1: note: candidate template ignored: couldn't infer template argument '_Rp'
bind(_Fp&& __f, _BoundArgs&&... __bound_args)

我正在使用的代码:

#include <pybind11/numpy.h>
#include <boost/mp11.hpp>
#include <functional>

using boost::mp11::mp_product;
using boost::mp11::mp_for_each;

template <typename...> struct type_list {};

// all possible types
using my_type_list = type_list<
  double, float, py::ssize_t, int, unsigned int, unsigned long>;

// construct all possible pairs of types with help from boost::mp11
using my_type_pairs = mp_product<
  type_list, my_type_list, my_type_list>;

// the C++ function that we bind to a python module in the next function.
template <typename Tx, typename Ty>
py::array<py::ssize_t> foo(p::array_t<Tx> x, py::array_t<Ty>) {
  py::array_t<py::ssize_t> z;
  // do something with x and y
  return z;
}

// bind foo<Tx, Ty> function to py::module m
template <typename Tx, typename Ty>
void inject_foo(py::module_& m, const type_list<Tx, Ty>&) {
  m.def("_foo", &foo<Tx, Ty>, py::arg("x").noconvert(), py::arg("y").noconvert());
}

PYBIND11_MODULE(_backend, m) {
  // these function calls work as expected:
  // inject_foo(m, type_list<double, double>{});
  // inject_foo(m, type_list<double, float>{});
  // inject_foo(m, type_list<double, int>{});
  // .....

  // trying to make my life easier with the loop 
  // over all possible types of pairs is not working
  mp_for_each(pg_type_pairs{}, std::bind(inject_foo, m, std::placeholders::_1));

}
4

1 回答 1

1

PiotrNycz 的评论引出了一个答案:

mp_for_each<pg_type_pairs>([&](const auto& x) { inject_foo(m, x); });

提供所需的行为(在这个问题中,我什mp_for_each至错误地使用了 API;切换到 lambda 有助于发现该错误)。

于 2021-02-05T22:46:05.243 回答