VC ++ 2013中嵌套的可变参数模板化结构的别名

时间:2015-10-21 08:16:44

标签: c++ c++11 templates variadic-templates

对于模板化嵌套结构,我可以定义如下的别名:

template<typename T>struct Struct
{
    Struct(T value){}

    template<typename T1> struct Nested
    {
        Nested(T1 value){}
    };
};
template<typename T, typename T1>using NameT = struct Struct<T>::Nested<T1>;
using Name = NameT<int, double>; // Alias for a certain instance

有人可以给我一个提示如何声明可变参数的别名吗?

template<typename... T>struct Struct
{
    Struct(T... value){}

    template<typename T1> struct Nested
    {
        Nested(T1 value){}
    };
};
template<typename... T, typename T1>using NameT = struct Struct<T...>::Nested<T1>; // This seems ok
using Name = NameT<int, double>; // error C976: 'Name': too few template arguments

3 个答案:

答案 0 :(得分:2)

这将有效:

template<typename T1, typename... T>using NameT = 
   typename Struct<T...>::template Nested<T1>; // This seems ok
   ^^^^^^^^               ^^^^^^^^
using Name = NameT<int, double>;

请注意,参数包必须在末尾,因此定义会略有改变。

LIVE DEMO

答案 1 :(得分:1)

将您的代码更改为:

template<typename... T>
struct Struct
{
    Struct(T... value){}

    template<typename T1>
    struct Nested
    {
        Nested(T1 value){}
    };
};

template<typename T1, typename... T>
using NameT = typename Struct<T...>::template Nested<T1>;
using Name = NameT<int, double>;

    int main()
    {    
        Name f(1);
    }

可变参数模板必须位于模板参数列表的末尾。

答案 2 :(得分:0)

#include <type_traits>
#include <tuple>
#include <utility>

template <typename... T>
struct Struct
{
    Struct(T... value) {}

    template <typename T1>
    struct Nested
    {
        Nested(T1 value) {}
    };
};

template <typename, typename>
struct split;

template <typename T, std::size_t... Is>
struct split<T, std::index_sequence<Is...>>
{
    using type = typename Struct<typename std::tuple_element<Is, T>::type...>::template Nested<typename std::tuple_element<sizeof...(Is), T>::type>;
};

template <typename... T>
using NameT = typename split<std::tuple<T...>, std::make_index_sequence<sizeof...(T)-1>>::type;

int main()
{
    static_assert(std::is_same<NameT<int, double, char>
                             , Struct<int, double>::Nested<char>>{}, "!");
}

DEMO