且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

可变参数可变参数模板模板

更新时间:2022-10-27 09:08:55

尝试如下操作:

template <typename...> struct join;

template <template <typename...> class Tpl,
          typename ...Args1,
          typename ...Args2>
struct join<Tpl<Args1...>, Tpl<Args2...>>
{
    typedef Tpl<Args1..., Args2...> type;
};

template <template <typename...> class Tpl,
          typename ...Args1,
          typename ...Args2,
          typename ...Tail>
struct join<Tpl<Args1...>, Tpl<Args2...>, Tail...>
{
     typedef typename join<Tpl<Args1..., Args2...>, Tail...>::type type;
};

I'm currently struggling with the following code, the intent of which is to implement variadic variadic template templates:

template
<
  template <typename... HeadArgs> class Head,
  template <typename... TailArgs> class...
>
struct join<Head<typename HeadArgs...>, Head<typename TailArgs...>...>
{
  typedef Head<typename HeadArgs..., typename TailArgs......> result;
};

Ideally, I'd be able to use this template metafunction to achieve the following:

template <typename...> struct obj1 {};
template <typename...> struct obj2 {};

typedef join
<
  obj1<int, int, double>, 
  obj1<double, char>,
  obj1<char*, int, double, const char*>
>::result new_obj1;

typedef join
<
  obj2<int, int, double>, 
  obj2<double, char>,
  obj2<char*, int, double, const char*>
>::result new_obj2;

/* This should result in an error, because there are 
   different encapsulating objects
typedef join
<
  obj1<int, int, double>, 
  obj1<double, char>,
  obj2<char*, int, double, const char*>
>::result new_obj;
*/

The output of the above would hopefully create new_obj1 and new_obj2 in the form template<int, int, double, double, char, char*, int, double, const char*> struct new_obj[1|2] {};

I'm using gcc 4.6.2 on Windows, which outputs an "expected parameter pack before '...'" for the expansion of "Head<typename TailArgs...>...".

This error is reproducable with gcc 4.5.1.

Try something like this:

template <typename...> struct join;

template <template <typename...> class Tpl,
          typename ...Args1,
          typename ...Args2>
struct join<Tpl<Args1...>, Tpl<Args2...>>
{
    typedef Tpl<Args1..., Args2...> type;
};

template <template <typename...> class Tpl,
          typename ...Args1,
          typename ...Args2,
          typename ...Tail>
struct join<Tpl<Args1...>, Tpl<Args2...>, Tail...>
{
     typedef typename join<Tpl<Args1..., Args2...>, Tail...>::type type;
};