75

この問題に遭遇したとき、私は C++0x 可変個引数テンプレートを試していました:

template < typename ...Args >
struct identities
{
    typedef Args type; //compile error: "parameter packs not expanded with '...'
};

//The following code just shows an example of potential use, but has no relation
//with what I am actually trying to achieve.
template < typename T >
struct convert_in_tuple
{
    typedef std::tuple< typename T::type... > type;
};

typedef convert_in_tuple< identities< int, float > >::type int_float_tuple;

テンプレート パラメーター パックを typedef しようとすると、GCC 4.5.0 でエラーが発生します。

基本的に、パラメータパックを解凍せずにtypedefに「保存」したいと思います。出来ますか?そうでない場合、これが許可されていない理由はありますか?

4

4 に答える 4

57

Ben の方法よりも少し一般的な別の方法は次のとおりです。

#include <tuple>

template <typename... Args>
struct variadic_typedef
{
    // this single type represents a collection of types,
    // as the template arguments it took to define it
};

template <typename... Args>
struct convert_in_tuple
{
    // base case, nothing special,
    // just use the arguments directly
    // however they need to be used
    typedef std::tuple<Args...> type;
};

template <typename... Args>
struct convert_in_tuple<variadic_typedef<Args...>>
{
    // expand the variadic_typedef back into
    // its arguments, via specialization
    // (doesn't rely on functionality to be provided
    // by the variadic_typedef struct itself, generic)
    typedef typename convert_in_tuple<Args...>::type type;
};

typedef variadic_typedef<int, float> myTypes;
typedef convert_in_tuple<myTypes>::type int_float_tuple;

int main()
{}
于 2011-01-14T16:42:39.347 に答える
10

それが許可されない理由は、それが厄介であり、あなたがそれを回避することができるからだと思います。依存性逆転を使用し、パラメーターパックをファクトリテンプレートに格納する構造体を作成して、そのパラメーターパックを別のテンプレートに適用できるようにする必要があります。

次のようなもの:

template < typename ...Args >
struct identities
{
    template < template<typename ...> class T >
    struct apply
    {
        typedef T<Args...> type;
    };
};

template < template<template<typename ...> class> class T >
struct convert_in_tuple
{
    typedef typename T<std::tuple>::type type;
};

typedef convert_in_tuple< identities< int, float >::apply >::type int_float_tuple;
于 2011-01-14T14:31:46.747 に答える
2

これは、GManNickG の巧妙な部分特化トリックのバリエーションです。委任はなく、variadic_typedef 構造体の使用を要求することで、型の安全性が向上します。

#include <tuple>

template<typename... Args>
struct variadic_typedef {};

template<typename... Args>
struct convert_in_tuple {
    //Leaving this empty will cause the compiler
    //to complain if you try to access a "type" member.
    //You may also be able to do something like:
    //static_assert(std::is_same<>::value, "blah")
    //if you know something about the types.
};

template<typename... Args>
struct convert_in_tuple< variadic_typedef<Args...> > {
    //use Args normally
    typedef std::tuple<Args...> type;
};

typedef variadic_typedef<int, float> myTypes;
typedef convert_in_tuple<myTypes>::type int_float_tuple; //compiles
//typedef convert_in_tuple<int, float>::type int_float_tuple; //doesn't compile

int main() {}
于 2013-02-18T01:08:38.427 に答える