3

数値シーケンスでパラメーターパックをアンパックする方法 (または可能)? 例えば、

template <typename C, typename... T>
C* init_from_tuple(bp::tuple tpl)
{
   return new C{bp::extract<T>("magic"(tpl))...}; // <--
}

<--行を展開する必要がある

   return new C{bp::extract<T0>(tpl[0]),
                bp::extract<T1>(tpl[1]),
                .....
                bp::extract<Tn>(tpl[n])};

どこでn == sizeof...(T) - 1

目的は、定義済みの型を持つタプルを受け入れる Boost.Python の __init__ 関数を作成することです。

4

2 に答える 2

3

実際には、アンパック操作で 2 つの異なるパラメーターのパックを一度にターゲットにすることができます (それらは同じ長さである必要があると思います)。ここでは、型のパックと数値のパックが必要です。

次のようなもの:

template <typename C, typename... T, size_t... N>
C* init_from_tuple_impl(bp::tuple tpl) {
  return new C{ bp::extract<T>(tpl[N])... };
}

インデックスのパックを生成する必要があるのは「ただ」:

template <size_t... N> struct Collection {};

template <typename C> struct ExtendCollection;

template <size_t... N>
struct ExtendCollection< Collection<N...> > {
  typedef Collection<N..., sizeof...(N)> type;
};

template <typename... T>
struct GenerateCollection;

template <>
struct GenerateCollection<> { typedef Collection<> type; };

template <typename T0, typename... T>
struct GenerateCollection<T0, T...> {
  typedef typename ExtendCollection<
    typename GenerateCollection<T...>::type
  >::type type;
};

そしてそれを使用します:

template <typename C, typename... T, size_t... N>
C* init_from_tuple_impl(bp::tuple tpl, Collection<N...>) {
  return new C { bp::extract<T>(tpl[N])... };
}

template <typename C, typename... T>
C* init_from_tuple(bp::tuple tpl) {
  typename GenerateCollection<T...>::type collection;
  return init_from_tuple_impl<C, T...>(tpl, collection);
}

イデオネで活動中。

次の実装で「間違い」を犯すことで、正しさを確認できます(たとえば、をinit_from_tuple_impl削除します)。new

template <typename C, typename... T, size_t... N>
C* init_from_tuple_impl(bp::tuple tpl, Collection<N...>) {
  return C { bp::extract<T>(tpl[N])... };
}

Ideoneでの活動:

prog.cpp: In function 'C* init_from_tuple_impl(bp::tuple, Collection<N ...>)
[with
    C = bp::Object,
    T = {int, float, char},
    unsigned int ...N = {0u, 1u, 2u},
    bp::tuple = std::basic_string<char>
]':

まさに私たちが望んでいたものです:)

于 2011-11-06T16:11:31.333 に答える
1

最初にパラメーターを独自のパックに抽出してからコンストラクターを呼び出すと、それが可能になります。完成にはほど遠いですが、一般的な考え方は次のとおりです。

template <typename C, int N, typename... T>
C* init_from_tuple(bp::tuple tpl, T... args) // enable_if N == sizeof...(T)
{
    return new C{args...};
}

template <typename C, int N, typename T0, typename... T>
C* init_from_tuple(bp::tuple tpl, T... args) // enable_if N != sizeof...(T)
{
    return init_from_tuple<C, N + 1>(tpl, args, bp::extract<T0>(tpl[N]));
}

template <typename C, typename... T>
C* init_from_tuple(bp::tuple tpl, T... args)
{
    return init_from_tuple<C, 0, T...>(tpl, args);
}

ブーストを使用enable_ifして、示された場所が特定の場合にのみ有効になるようにします。おそらく、テンプレート引数にいくつかの変更が必要ですが、これは始まりです。

于 2011-11-06T15:23:49.533 に答える