可以写这样的东西"f<N> can compile only when N>0"吗?

Is possible to write something like that "f<N> can compile only when N>0"?

本文关键字:gt can compile when only lt      更新时间:2023-10-16

例如,我可以在编译时检查N是否> 0,如下所示:

#include <stdio.h>
template<int N>
struct Is{
    enum{Positive=N>0?1:0};
};
template<>
    struct Is<0>{
};
int main(){
    printf("%dn",Is<3>::Positive);
    printf("%dn",Is<-3>::Positive);
    return 0;
};

通过强制Is<0>::Positive过滤0不能编译,但是是否有任何方法(例如:template,macro....)强制Is<当N不> 0时,N>::Positive不能编译?

static_assert(N > 0, "N must be greater than zero")