在包装使用返回类型为“ auto”的重载函数时,我需要帮助。 例如,https://machinelearningmastery.com/difference-test-validation-datasets/
上第699和708行的功能 SEAL_NODISCARD inline auto &scale() noexcept
{
return scale_;
}
SEAL_NODISCARD inline auto &scale() const noexcept
{
return scale_;
}
当我尝试如下绑定时,
py::class_<Ciphertext>(m, "Ciphertext")
.def("scale", (auto (Ciphertext::*)() const)&Ciphertext::scale, "returns a constant reference to the scale")
我看到此错误
...mseal.cpp:223:18: error: invalid use of ‘auto’
.def("scale", (auto (Ciphertext::*)() const)&Ciphertext::scale, "returns a constant reference to the scale")
我正在使用C ++ 17和python3。我不想修改C ++ SEAL库。 谢谢。
答案 0 :(得分:0)
编辑:我刚刚发现pybind11具有一个可以完成相同操作的帮助程序构造,从而导致了更简单/更简洁的代码。将原始答案中的<?php
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
class ActivateUser
{
/**
* Handle the event.
*
* @param Illuminate\Auth\Events\Login $event
* @return void
*/
public function handle(Login $event)
{
$event->user->fill('active', 1)->save();
}
}
块替换为:
PYBIND11_MODULE
原始答案:您将需要PYBIND11_MODULE(mseal, m) {
py::class_<Ciphertext>(m, "Ciphertext")
.def(py::init<>())
.def("scale",
py::overload_cast<>(&Ciphertext::scale, py::const_),
"returns a constant reference to the scale")
.def("scale_nonconst",
py::overload_cast<>(&Ciphertext::scale),
"returns a reference to the scale");
}
来获得返回类型,并且需要decltype
来消除std::declval
的过载。下面是一个完整的工作示例(最低C ++ 14),我在其中添加了非const版本只是为了表明您可以完全控制其中一个的选择:
decltype
其中,当编译为#include <pybind11/pybind11.h>
#include <pybind11/pytypes.h>
#include <iostream>
#include <utility>
namespace py = pybind11;
class Ciphertext {
public:
inline auto &scale() noexcept {
std::cerr << "non-const called" << std::endl;
return scale_;
}
inline auto &scale() const noexcept {
std::cerr << "const called" << std::endl;
return scale_;
}
private:
int scale_;
};
PYBIND11_MODULE(mseal, m) {
py::class_<Ciphertext>(m, "Ciphertext")
.def(py::init<>())
.def("scale",
static_cast<decltype(std::declval<Ciphertext const&>().scale()) (Ciphertext::*)() const>(&Ciphertext::scale),
"returns a constant reference to the scale")
.def("scale_nonconst",
static_cast<decltype(std::declval<Ciphertext&>().scale()) (Ciphertext::*)()>(&Ciphertext::scale),
"returns a reference to the scale");
}
时,可以按预期工作:
mseal.so