【发布时间】:2016-04-24 08:39:13
【问题描述】:
我想创建一个包含硬编码元素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{
是什么原因?它只是模板中的语法错误吗?或者这个想法是不可能的?如果不可能,有没有其他方法可以在编译时检查数组是否排序?
【问题讨论】:
-
Consexpr 函数应该简单得多。
-
g++和clang++都给我一个关于模板“重新声明”的错误,这是一个重要的错误。
标签: c++ arrays sorting templates compile-time