[C++编译时断言]:如果不满足某些条件,我们可以抛出编译错误吗?

Mci*_*anM 7 c++ templates assert compile-time

我写了一个函数:

template<int N> void tryHarder() {
    for(int i = 0; i < N; i++) {
        tryOnce();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是如果N在0到10之间,我只想要编译它.我可以这样做吗?怎么样?

jro*_*rok 14

你可以用static_assert声明来做:

template<int N> void tryHarder() {

    static_assert(N >= 0 && N <= 10, "N out of bounds!");

    for(int i = 0; i < N; i++) {
        tryOnce();
    }
}
Run Code Online (Sandbox Code Playgroud)

此功能仅在C++ 11之后可用.如果您遇到C++ 03,请查看Boost的静态断言宏.

这个的全部想法是很好的错误消息.如果你不关心那些,或者甚至不能提升,你可以做如下的事情:

template<bool B>
struct assert_impl {
    static const int value = 1;
};

template<>
struct assert_impl<false> {
    static const int value = -1;
};

template<bool B>
struct assert {
    // this will attempt to declare an array of negative
    // size if template parameter evaluates to false
    static char arr[assert_impl<B>::value]; 
};

template<int N>
void tryHarder()
{
    assert< N <= 10 >();
}

int main()
{
    tryHarder<5>();  // fine
    tryHarder<15>();  // error, size of array is negative
}
Run Code Online (Sandbox Code Playgroud)

  • @MatsPetersson作为模板参数,似乎是一个安全的假设它是一个编译时常量. (5认同)