boost/python/implicit.hpp

はじめに

implicitly_convertible は、Python オブジェクトを C++ 引数型に対して照合するとき、C++ の暗黙・明示的な変換について暗黙的な利用を可能にする。

関数

implicitly_convertible 関数テンプレート

template<class Source, class Target>
void implicitly_convertible()
テンプレートパラメータ
  • Source -- 暗黙の変換における元の型

  • Target -- 暗黙の変換における対象の型

要件

宣言 Target t(s); が合法である(sSource 型)。

効果

Source の rvalue を生成する登録済み変換器が 1 つでも存在する場合、あらゆる PyObject * p について変換が成功する Target rvalue への from_python 変換器を登録する。

根拠

C++ ユーザは、C++ で行っているような相互運用性を Python で利用できると考える。

C++ のモジュール定義
#include <boost/python/class.hpp>
#include <boost/python/implicit.hpp>
#include <boost/python/module.hpp>

using namespace boost::python;

struct X
{
    X(int x) : v(x) {}
    operator int() const { return v; }
    int v;
};

int x_value(X const& x)
{
    return x.v;
}

X make_x(int n) { return X(n); }

BOOST_PYTHON_MODULE(implicit_ext)
{
    def("x_value", x_value);
    def("make_x", make_x);

    class_<X>("X",
        init<int>())
        ;

    implicitly_convertible<X,int>();
    implicitly_convertible<int,X>();
}
Python のコード
>>> from implicit_ext import *
>>> x_value(X(42))
42
>>> x_value(42)
42
>>> x = make_x(X(42))
>>> x_value(x)
42