所以我正在做一些作业,我必须在 C++11 中编写自己的编译时整数序列并为其编写一些函数(打印、连接、排序等),但我有我在思考如何着手编写这些东西时遇到了一些麻烦。
template<typename T, typename Comp = std::less<int>>
struct Facility{
template<T ... Nums>
struct List{
struct Element<T ... nums>{};
template<unsigned num, T val, T ... rest>
struct Element{
unsigned index = num;
T value = val;
Element<index-1, rest...> others;
};
template<unsigned num, T val, T ... rest>
struct Element<0, val>{
unsigned index = 0;
T value = val;
};
static constexpr Element<sizeof...(Nums)-1,Nums...> elem = {};
static void Print()
{
// Prints out the list
}
};
};
using IntList = typename Facility<int>::List<intlist...>;
int main()
{
using List1 = IntList<1, 2, 3>;
List1::print()
}
我只是想知道我是否在正确的轨道上,这样我就不会把自己逼入死胡同。我不是 100% 确定 static print()
和 List
中的 static constexpr
成员,尽管我想不出任何使它起作用的其他方法。
最佳答案
不要像那样不必要地嵌套类型。写一个<T,Ts...>
顺序。
不要将操作耦合到类型。在外部写入操作(tail、head)。
从 std::integer_sequence<T,T...>
中汲取灵感在 C++14 中。
如果您需要在 OP 中描述的接口(interface),请改用平面接口(interface)。
到目前为止,最容易编写的排序是归并排序。
利用std::integral_constant
,这是 C++11。编写一个元函数,它接受一个模板模板参数和一个整数列表,并将每个整数常量作为类型传递给,并生成一个类型列表 template<class...Ts>struct types{};
作为输出。称之为 foreach_int
编写 foreach_type,它接受一个类型列表并在每个元素上调用一个函数对象。现在打印是微不足道的; template<class list> void print_list(){ foreach_type( foreach_int< idenitity, list >{}, print{} ); }
其中 template<cls T> void print(T && t}{std::cout<<t;}
这些中的每一个都更容易推理,并且组合它们可以让您“打印每个”。
但也许我有点疯狂。
关于c++ - 在 C++11 中打印编译时整数序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45272221/