如何static_cast一个指向const成员函数的指针?

How to static_cast a pointer to const member function?

令人惊讶(尴尬?)我无法正确理解 const 成员函数的 static_const 的语法。总之(下面有详细说明)如果成员函数不标const我用:

static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&)>(&mymodule::Foo::bar)

但是标记成员函数Foo::bar(...) const编译器不知道该做什么:

error: address of overloaded function 'bar' cannot be static_cast to type 'std::vector<double> (mymodule::Foo::*)(const std::vector<double> &)'

我应该把函数的 const 放在哪里?

详情

我正在尝试为以下模块创建 Python 绑定:

namespace mymodule {

class Foo
{
public:

    Foo() = default;

    template <class T>
    T bar(const T& a) const
    {
        T ret = a;
        for (auto& i : ret) {
            i *= 2.0;
        }
        return ret;
    }

    template <class T>
    T bar(const T& a, double f) const
    {
        T ret = a;
        for (auto& i : ret) {
            i *= f;
        }
        return ret;
    }

};

} // namespace mymodule

我用 pybind11 编写 Python 绑定:

#include <pybind11/pybind11.h>

namespace py = pybind11;

PYBIND11_MODULE(example, m)
{
    py::class_<mymodule::Foo>(m, "Foo")
        .def(py::init<>())

        .def("bar",
             static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&)>(&mymodule::Foo::bar),
             py::arg("a"))

        .def("bar",
             static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&, double)>(&mymodule::Foo::bar),
             py::arg("a"),
             py::arg("f"));
}

编译失败:

.../example.cpp:54:14: error: address of overloaded function 'bar' cannot be static_cast to type 'std::vector<double> (mymodule::Foo::*)(const std::vector<double> &)'
             static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&)>(&mymodule::Foo::bar),
             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.../example.cpp:19:7: note: candidate function template
    T bar(const T& a) const
      ^
.../example.cpp:29:7: note: candidate function template
    T bar(const T& a, double f) const
      ^
.../example.cpp:58:14: error: address of overloaded function 'bar' cannot be static_cast to type 'std::vector<double> (mymodule::Foo::*)(const std::vector<double> &, double)'
             static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&, double)>(&mymodule::Foo::bar),
             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.../example.cpp:19:7: note: candidate function template
    T bar(const T& a) const
      ^
.../example.cpp:29:7: note: candidate function template
    T bar(const T& a, double f) const
      ^
2 errors generated.

您应该在最后添加 const 作为:

static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&) const>(&mymodule::Foo::bar),
//                                                                             ^^^^^