我想创建一个程序,其中包含硬编码元素 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/