小编Adr*_*anH的帖子

Pybind11 - 返回指向 unique_ptr 容器的指针

我一直在使用优秀的 pybind11 库,但遇到了麻烦。我需要向 Python 返回一个指向不可复制对象的指针(因为该对象包含 unique_ptrs)。

通常,这可以正常工作,但需要注意使用 return_value_policy::reference。但是,返回指向具有不可复制向量的对象的指针会导致编译错误。在这种情况下,pybind 似乎想要执行复制,即使返回值策略是引用并且函数显式返回一个指针。

为什么会这样,是否有解决方法?

我正在使用 VS2017 15.9.2 和最新的 pybind11 off master

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <vector>
#include <memory>

/* This fails to compile... */
struct myclass
{
    std::vector<std::unique_ptr<int>> numbers;
};

/* ...but this works
struct myclass
{
    std::unique_ptr<int> number;
};
*/

void test(py::module &m)
{
    py::class_<myclass> pymy(m, "myclass");

    pymy.def_static("make", []() {
        myclass *m = new myclass;
        return m;
    }, py::return_value_policy::reference);
}
Run Code Online (Sandbox Code Playgroud)

pybind11

5
推荐指数
1
解决办法
1138
查看次数

C++ 20 概念/Requires 子句

如果有人能解释 C++ 20+ 编译器(在我的例子中是 MSVC 2022)如何能够编译以下内容,我将非常感激,为什么简单概念没有效果?

template <typename T>
concept Simple = requires(T t)
{
    std::is_trivial_v<T> == true;
};


void foo(Simple auto s) {
    std::cout << "bar";
}


int main(int argc, char** argv)
{
    using Bytes = std::span<std::byte>;

    Bytes b;

    static_assert(false == std::is_trivial_v<Bytes>);

    foo(b);  //compiles and prints "bar"
}
Run Code Online (Sandbox Code Playgroud)

c++ c++20

2
推荐指数
1
解决办法
710
查看次数

标签 统计

c++ ×1

c++20 ×1

pybind11 ×1