解释static_cast“ static_cast <voidPet :: *int>”语法吗?

问题描述

我正在尝试了解Pybind11 docs here中使用的静态转换。具体来说,他们使用语法

static_cast<void (Pet::*)(int)>(&Pet::set)

由于我在努力解释和应用到自己的代码之前还没有看到这种语法,所以我希望有人可以解释这里发生的事情。谢谢

编辑-一些上下文

我正在为具有两个签名的重载方法创建Pybind11绑定,这两个签名的区别仅在于const。我绑定的类是模板,因此我正在使用this strategy to create the bindings

    template<class T>
    class Matrix {
    public:

        ...

        /**
         * get the row names
         */
        std::vector<std::string> &getRowNames() {
            return rowNames;
        }

        /**
         * get the row names (mutable)
         */
        const std::vector<std::string> &getRowNames() {
            return rowNames;
        }

    ...

我在那篇文章中描述的helper函数的版本是这样的:

template<typename T>
void declare_matrix(py::module &m,const std::string &typestr) {
    using Class = ls::Matrix<T>;
    const std::string &pyclass_name = typestr;
    py::class_<Class>(m,pyclass_name.c_str(),py::buffer_protocol(),py::dynamic_attr())
            .def(py::init<unsigned int,unsigned int>())
            .def("getRowNames",static_cast<const std::vector<std::string>(ls::Matrix<T>::*)()>(&ls::Matrix<T>::getRowNames))

但是getRowNames行会产生以下错误

Address of overloaded function 'getRowNames' cannot be static_cast to type 'const std::vector<std::string> (ls::Matrix<complex<double>>::*)()'

对于其他阅读本文的人来说,我的答案是:

static_cast< std::vector<std::string>& (ls::Matrix<T>::*)()>(&Class::getRowNames)

解决方法

含义:

static_cast<void (Pet::*)(int)>(&Pet::set)
  • static_cast<T_1>(T_2)表示我们将类型2转换为类型1。
  • T_1
    • (Pet::*)是Pet类成员的指针(有关进一步的讨论,请参见https://stackoverflow.com/a/9939367/14344821
    • void (Pet::*)(int)是指向成员函数的指针,该成员函数使用一个int参数,并返回一个void
  • T_2
    • &Pet::setPet::set
    • 的存储位置

因此,基本上,我们明确表示要设置整数值

现在我们可以将set函数 s 绑定到python(允许我们同时设置年龄和名称):

   .def("set",static_cast<void (Pet::*)(int)>(&Pet::set),"Set the pet's age")
   .def("set",static_cast<void (Pet::*)(const std::string &)>(&Pet::set),"Set the pet's name");

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...