c++ - 如何使用模板递归检查硬编码 int 数组是否在编译时排序?

标签 c++ arrays sorting templates compile-time

我想创建一个程序,其中包含硬编码元素 L(例如:1,2,3,3)的数组,并使用模板变量参数来检查元素是否已排序,如果未排序,将失败在 static_assert 处编译,但现在程序根本无法编译:

#include <stdio.h>
#include <vector>
template<int first,int second,int... args>
struct s{
    enum{e=first<=second && s<second,args...>::e};
};

template<int first,int second>
struct s{
    enum{e=first<=second};
};
#define L 1,2,3,3
//static_assert(s<L>::e!=0,"");
int a[]={L};
int main(){
    printf("%d\n",s<L>::e);
    return 0;
}

编译错误说:

abc.cpp:5:29: error: too few template arguments for class template 's'
    enum{e=first<=second && s<second,args...>::e};
                        ^
abc.cpp:5:29: note: in instantiation of template class 's<3, 3>' requested here
    enum{e=first<=second && s<second,args...>::e};
                        ^
abc.cpp:5:29: note: in instantiation of template class 's<2, 3, 3>' requested here
    enum{e=first<=second && s<second,args...>::e};
                        ^
abc.cpp:16:19: note: in instantiation of template class 's<1, 2, 3, 3>' requested here
    printf("%d\n",s<L>::e);
              ^
abc.cpp:4:8: note: template is declared here
    struct s{

这是什么原因?它只是模板中的语法错误吗?或者这个想法是不可能的?如果不可能,是否有其他方法可以在编译时检查数组是否已排序?

最佳答案

您需要部分模板特化。

template<int... Args>
struct IsSorted {
    static constexpr bool value = true;
};

template<int A, int B, int... Args>
struct IsSorted<A, B, Args...> {
    static constexpr bool value = A <= B && IsSorted<B, Args...>::value;
};

int main() {
    static_assert(IsSorted<>::value, "");
    static_assert(IsSorted<1>::value, "");
    static_assert(IsSorted<1, 2>::value, "");
    static_assert(!IsSorted<2, 1>::value, "");
    static_assert(IsSorted<1, 2, 3>::value, "");
    static_assert(!IsSorted<1, 3, 2>::value, "");
}

关于c++ - 如何使用模板递归检查硬编码 int 数组是否在编译时排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34867205/

相关文章:

java - 如何将n个数字相加,相乘到数组中的给定范围,并以O(n)时间反转数组中的范围?

Python:通过另一个函数中的参数对列表进行排序

C 中整数的计数排序列表

c++ - 获取 Windows 监视器的唯一标识符

c++ - 类型删除和访问器

c++ - 如何指示容器模板参数的类型?

java - 如何在插入排序中保持数据配对

jquery - 检查数组是否为空或 null

python - Python 中的哪种数据结构可用于替换 Excel 2-dim 字符串/数量数组?

oracle - 将 Oracle 上的结果排序为 ASCII