boost/python/enum.hpp

はじめに

<boost/python/enum.hpp> は、ユーザが C++ 列挙型を Python へエクスポートするためのインターフェイスを定義する。エクスポートする列挙型を引数に持つ enum_ クラステンプレートを宣言する。

クラス

enum_<T> クラステンプレート

template<class T>
class enum_ : public object

第 1 引数に渡した C++ 型に対応する、Python の int 型から派生した Python クラスを作成する。

namespace boost { namespace python
{
  template <class T>
  class enum_ : public object
  {
    enum_(char const* name, char const* doc = 0);
    enum_<T>& value(char const* name, T);
    enum_<T>& export_values();
  };
}}

enum_ クラステンプレートのコンストラクタ

enum_(char const *name, char const *doc = 0)
要件

name は Python の識別子の名前付け規約にしたがった ntbs

効果

名前 nameint から派生した Python 拡張型を保持する enum_ オブジェクトを構築する。現在のスコープの名前 name の属性を新しい列挙型に束縛する。

enum_ クラステンプレートの変更関数

inline enum_<T> &value(char const *name, T x)
要件

name は Python の識別子の名前付け規約にしたがった ntbs

効果

ラップした列挙型のインスタンスを名前 name 、値 x とともに型の辞書へ追加する。

inline enum_<T> &export_values()
効果

value の呼び出しでエクスポートしたすべての列挙値を同じ名前で現在の scope の属性として設定する。

戻り値

*this

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

using namespace boost::python;

enum color { red = 1, green = 2, blue = 4 };

color identity_(color x) { return x; }

BOOST_PYTHON_MODULE(enums)
{
    enum_<color>("color")
        .value("red", red)
        .value("green", green)
        .export_values()
        .value("blue", blue)
        ;

    def("identity", identity_);
}
Python の対話コード
>>> from enums import *

>>> identity(red)
enums.color.red

>>> identity(color.red)
enums.color.red

>>> identity(green)
enums.color.green

>>> identity(color.green)
enums.color.green

>>> identity(blue)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name blue' is not defined

>>> identity(color.blue)
enums.color.blue

>>> identity(color(1))
enums.color.red

>>> identity(color(2))
enums.color.green

>>> identity(color(3))
enums.color(3)

>>> identity(color(4))
enums.color.blue

>>> identity(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: bad argument type for built-in operation