2017-06-22 22 views
0

我想在C++ 11中使用vadiadic模板来定义一个IntList类,但是我在语法上遇到困难,我不知道如何初始化班级领域。使用可变参数模板在C++中定义一个列表类

我的最新版本如下:

template <int...> 
struct IntList; 

template<> 
struct IntList<>{ 
    constexpr static bool empty = true; 
    constexpr static int size = 0; 
}; 

template<int Hd> 
struct IntList<Hd>{ 
    constexpr static bool empty = false; 
    constexpr static int size = 1; 
    constexpr static int head = Hd; 
    constexpr static IntList<> next = IntList<>(); 
}; 

template<int Hd, int... Rs> 
struct IntList<Hd, Rs...>{ 
    constexpr static bool empty = false; 
    constexpr static int size = sizeof ...(Rs); 
    constexpr static int head = Hd; 
    constexpr static IntList<Rs...> next = IntList<Rs...>(); 
}; 

我的目录类有4个字段,用头场返回列表的第一个数字和下一场返回列表中的“尾巴”。

对于包含2个或更多数字和2个基本情况的列表,包含1个数字的列表和一个空列表(它不包含头部和下一个字段)(空列表应抛出一个尝试访问其中一个时发生错误)。

当试图测试我的列表,该行:

IntList<1, 2, 3>::next::next; 

使我有以下错误:

error: 'IntList<1, 2, 3>::next' is not a class, namespace, or enumeration 
    IntList<1, 2, 3>::next::next; 

试图界定头部和下一场普通(非静态)域并在构造函数中初始化它们也会导致错误:

invalid use of non-static data member 'IntList<1, 2, 3>::head' 
    IntList<1, 2, 3>::head; 

这使我相信事实上,我应该将这两个字段定义为“静态”。

关于如何定义头部的任何输入&下一个字段/我做错了什么,将不胜感激!

+1

您有一个可能模糊的过载情况。 'IntList <1>'将被'struct IntList '和'struct IntList '与空的可变参数列表匹配。你可以完全摆脱第二个模板声明。 –

+0

你为什么要这样做? – Walter

+2

你知道有[std :: integer_sequence](http://en.cppreference.com/w/cpp/utility/integer_sequence),对吧? – MadScientist

回答

5

你可能要声明一个类型,而不是一个静态成员:

using next = IntList<Rs...>; 

Demo

+0

更改行: 'constexpr静态intList中未来= intList中();' 到错误你建议的结果: '错误:声明没有宣布任何东西[-fpermissive] intList中<1, 2, 3> ::下一: :next;' – Alice312

+0

@ Alice312:我刚刚添加了演示链接。 – Jarod42

1

这应该做你想做的,在大约一半的代码:

template<int...> 
struct ints { 
    constexpr static bool empty = true; 
    constexpr static int size = 0; 
}; 

template<int I0, int... Is> 
struct ints<I0, Is...>{ 
    constexpr static bool empty = false; 
    constexpr static int size = 1+sizeof...(Is); 
    constexpr static int head = I0; 
    using next = ints<Is...>; 
}; 

现在:

using just_three = ints<1, 2, 3>::next::next; 
static_assert(std::is_same<ints<3>, just_three>::value, "{3}=={3}"); 

测试它。

Live example

相关问题