如何将指针静态转换为 const 成员函数?

Tom*_*eus 3 c++ constants pointer-to-member pybind11

static_const令人惊讶(尴尬?)我无法正确理解成员函数的语法const。简而言之(详细信息如下)如果未标记成员函数const我使用:

static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&)>(&mymodule::Foo::bar)
Run Code Online (Sandbox Code Playgroud)

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

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

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

细节

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

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

我用 pybind11 编写 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
Run Code Online (Sandbox Code Playgroud)

无法编译:

#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"));
}
Run Code Online (Sandbox Code Playgroud)

son*_*yao 5

您应该const最后添加为:

static_cast<std::vector<double> (mymodule::Foo::*)(const std::vector<double>&) const>(&mymodule::Foo::bar),
//                                                                             ^^^^^
Run Code Online (Sandbox Code Playgroud)