How to print result of a compile-time calculation in C++?

后端 未结 5 819
刺人心
刺人心 2021-01-01 22:27

I\'ve wrote several constexpr functions and use them in static_asserts to control some resource limits. But I\'d like to not only enforce compile-time predicate but also to

5条回答
  •  悲&欢浪女
    2021-01-01 23:10

    Here is some code that exploits gcc's diagnostic messages to print values of interest after an assert message. To find the values of interest, you just need to search the error string for T x =:

    #include 
    
    template 
    void transparent(F f) { f(); }
    
    
    template 
    constexpr void my_assert() { 
        static_assert(B, "oh no");
    }
    
    template 
    void f() {
        transparent([]{
            transparent([]{
                my_assert(); });});
    }
    
    int main() {
    //    f<3>();
        f<4>();
    //    f<-99>();
    }
    

    Here is the error that it got me:

    g++ h.cpp -std=c++11
    h.cpp: In instantiation of ‘constexpr void my_assert() [with bool B = false]’:
    h.cpp:16:34:   required from ‘f() [with int X = 4]::__lambda0::__lambda1’
    h.cpp:15:35:   required from ‘struct f() [with int X = 4]::__lambda0::__lambda1’
    h.cpp:16:38:   required from ‘f() [with int X = 4]::__lambda0’
    h.cpp:14:28:   required from ‘struct f() [with int X = 4]::__lambda0’
    h.cpp:16:41:   required from ‘void f() [with int X = 4]’
    h.cpp:21:10:   required from here
    h.cpp:9:5: error: static assertion failed: oh no
         static_assert(B, "oh no");
         ^
    h.cpp:4:6: error: ‘void transparent(F) [with T = long int; T x = 64l; F = f() [with int X = 4]::__lambda0::__lambda1]’, declared using local type ‘f() [with int X = 4]::__lambda0::__lambda1’, is used but never defined [-fpermissive]
     void transparent(F f) { f(); }
          ^
    h.cpp:4:6: error: ‘void transparent(F) [with T = int; T x = 11; F = f() [with int X = 4]::__lambda0]’, declared using local type ‘f() [with int X = 4]::__lambda0’, is used but never defined [-fpermissive]
    

    Note that bolded parts

提交回复
热议问题