c++ - 具有通用引用/完美转发的 Boost.python?

标签 c++ perfect-forwarding universal-reference

我一直在试验 C++11 通用引用和一些类中的完美转发,这些类也需要使用 Boost.Python 从 Python 访问。我有有效的代码,但它需要在类之外进行一些丑陋的模板特化。有人以更优雅的方式解决了这个问题吗?有人对改进以下代码有任何建议吗?

#include <boost/python.hpp>
#include <string>

using namespace boost::python;

struct A {
    A() : _a("initial") {}

    template <typename T>
    void set_a(T&& a) { _a = std::forward<T>(a); }

    const std::string& get_a() const { return _a; }

private:
    std::string _a;
};

// How can the following template member function specialization be avoided?
template <>
void A::set_a(const std::string& a) { _a = a; }

BOOST_PYTHON_MODULE(example)
{
    class_<A>("A")
       .add_property("a", make_function( &A::get_a, return_value_policy<copy_const_reference>()),
                     &A::set_a<const std::string&>) // Can this be defined differently?
    ;
}

最佳答案

我今天做了一些实验,发现答案其实很简单。只需在 add_property 的 setr 部分再次使用 make_function() 即可:

这是简化的代码:

#include <boost/python.hpp>
#include <string>

using namespace boost::python;

struct A {
    A() : _a("initial") {}

    template <typename T>
    void set_a(T&& a) { _a = std::forward<T>(a); }

    const std::string& get_a() const { return _a; }

private:
    std::string _a;
};

BOOST_PYTHON_MODULE(example)
{
    class_<A>("A")
       .add_property("value",
                     make_function( &A::get_a, return_value_policy<copy_const_reference>()),
                     make_function( &A::set_a<const std::string&> )
    );
}

关于c++ - 具有通用引用/完美转发的 Boost.python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17916139/

相关文章:

iphone - iphone 应用程序的安全登录和 session 管理

c++ - 在访问引用类型的成员时总是使用左值是什么情况?

C++ - 如何将类上的所有成员函数调用委托(delegate)给同一接口(interface)的成员

c++ - 通过通用引用传递的函数的 std::forward?

c++ - 不转发通用引用会出现什么样的问题?

c++ - 我可以只为某些特化定义静态 constexpr 数据成员吗?

c++ - std::istreambuf_iterator "peek"与 std::ifstream

c++ - 具有模板化类的通用引用

c++ - 在编译时推导二维数组的一维

c++ - 通用引用与常量引用优先级?