问题描述
我正在尝试了解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;
}
...
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::set
是Pet::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");