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

时间:2023-03-10
本文介绍了是否可以“存储"?一个模板参数包而不扩展它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

当我偶然发现这个问题时,我正在试验 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()
{}

这篇关于是否可以“存储"?一个模板参数包而不扩展它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:C++ 模板,未定义的引用 下一篇:如何实现“虚拟模板功能"在 C++ 中

相关文章