是否可以“存储"?一个模板参数包而不扩展它?

2021-12-13 00:00:00 templates c++ c++11 variadic-templates

当我偶然发现这个问题时,我正在试验 C++0x 可变参数模板:

I was experimenting with C++0x variadic templates when I stumbled upon this issue:

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 给我一个错误.

GCC 4.5.0 gives me an error when I try to typedef the template parameters pack.

基本上,我想将参数包存储"在 typedef 中,而不需要解包.是否可以?如果不是,有什么原因不允许这样做吗?

Basically, I would like to "store" the parameters pack in a typedef, without unpacking it. Is it possible? If not, is there some reason why this is not allowed?

推荐答案

另一种比 Ben 稍微通用的方法如下:

Another approach, which is slightly more generic than Ben's, is as follows:

#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()
{}

相关文章