static_assert不会立即中断编译

Krz*_*tof 6 c++ templates static-assert c++11

代码示例:

template <int x>
struct SUM
{
    static_assert(x >= 0, "X must be greater or equal to 0");
    enum {VALUE = x + SUM<x-1>::VALUE};
};

template<>
struct SUM<0>
{
    enum {VALUE = 0};
};

int main()
{
    std::cout << SUM<-1>::VALUE << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么编译器不会破坏第一个static_assert上的编译,但继续工作直到达到最大实例化深度?

Invoking: GCC C++ Compiler
g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++11 -MMD -MP -MF"src/Main.d" -MT"src/Main.d" -o "src/Main.o" "../src/Main.cpp"
../src/Main.cpp: In instantiation of ‘struct SUM<-1>’:
../src/Main.cpp:47:22:   required from here
../src/Main.cpp:26:2: error: static assertion failed: X must be greater or equal to 0
  static_assert(x >= 0, "X must be greater or equal to 0");
  ^

......

../src/Main.cpp: In instantiation of ‘struct SUM<-2>’:
../src/Main.cpp: In instantiation of ‘struct SUM<-900>’:
../src/Main.cpp:27:18:   recursively required from ‘struct SUM<-2>’
../src/Main.cpp:27:18:   required from ‘struct SUM<-1>’
../src/Main.cpp:47:22:   required from here
../src/Main.cpp:26:2: error: static assertion failed: X must be greater or equal to 0
../src/Main.cpp:27:18: error: template instantiation depth exceeds maximum of 900 (use -ftemplate-depth= to increase the maximum) instantiating ‘struct SUM<-901>’
  enum {VALUE = x + SUM<x-1>::VALUE};
                  ^
../src/Main.cpp:27:18:   recursively required from ‘struct SUM<-2>’
../src/Main.cpp:27:18:   required from ‘struct SUM<-1>’
../src/Main.cpp:47:22:   required from here

../src/Main.cpp:27:18: error: incomplete type ‘SUM<-901>’ used in nested name specifier
make: *** [src/Main.o] Error 1

13:04:05 Build Finished (took 6s.877ms)
Run Code Online (Sandbox Code Playgroud)

这里唯一的问题是它需要花费很多时间才能打破,并产生大量的输出.有没有办法让这更好?使用的编译器:gcc版本4.8.1

小智 8

语言中没有任何内容需要编译才能立即中止,因此您直接回答问题的任何内容都必然是特定于实现的,并且不会避免其他实现的实例化.我认为更好的方法是以一种无法继续实例化的方式重新编写代码.一种可行的方法是std::enable_if:

#include <iostream>
#include <type_traits>

template <int x, typename = typename std::enable_if<x >= 0>::type>
struct SUM_impl
{
    enum {VALUE = x + SUM_impl<x-1>::VALUE};
};

template<>
struct SUM_impl<0>
{
    enum {VALUE = 0};
};

template <int x>
struct SUM
{
    static_assert(x >= 0, "X must be greater or equal to 0");
    enum {VALUE = SUM_impl<x>::VALUE};
};

int main()
{
    std::cout << SUM<-1>::VALUE << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这样,static_assertin就会SUM打印出用户友好的消息.将enable_ifSUM_impl强行拒绝任何地方x < 0,之前的模板会被实例化,如果模板不被实例化,它不能被递归要么实例化.

我最初是SUM从中衍生出来的SUM_impl,但是没有这样做(并且复制它的值)提供了更好的诊断.