"语法?-6ren"> "语法?-我正在尝试理解 Pybind11 docs here 中使用的静态转换.具体来说,他们使用语法 static_cast(&Pet::set) 因为在我努力解释并应用到我自己的代码之前我还没有见过这种语-6ren">
gpt4 book ai didi

c++ - 解释 static_cast "static_cast"语法?

转载 作者:行者123 更新时间:2023-12-03 06:58:42 26 4
gpt4 key购买 nike

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

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

因为在我努力解释并应用到我自己的代码之前我还没有见过这种语法,所以我希望有人能解释这里发生了什么。谢谢

编辑 - 一些上下文

我正在为具有两个签名的重载方法创建 Pybind11 绑定(bind),这两个签名仅在 const 限定上有所不同。我绑定(bind)的类是一个模板,所以我使用 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 :
  • T_2
    • &Pet::setPet::set的内存位置

基本上,我们明确声明我们正在设置整数值

现在我们可以绑定(bind) set functions 到 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");

关于c++ - 解释 static_cast "static_cast<void (Pet::*)(int)>"语法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64632424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com