C++ check if statement can be evaluated constexpr

后端 未结 3 1099
无人共我
无人共我 2020-12-23 11:50

Is there a method to decide whether something can be constexpr evaluated, and use the result as a constexpr boolean? My simplified use case is as follows:

te         


        
3条回答
  •  感动是毒
    2020-12-23 12:40

    Not exactly what you asked (I've developer a custom type trait specific for a get_value() static method... maybe it's possible to generalize it but, at the moment, I don't know how) but I suppose you can use SFINAE and make something as follows

    #include 
    #include 
    
    template 
    constexpr auto icee_helper (int)
       -> decltype( std::integral_constant{},
                    std::true_type{} );
    
    template 
    constexpr auto icee_helper (long)
       -> std::false_type;
    
    template 
    using isConstExprEval = decltype(icee_helper(0));
    
    template 
    struct derived
     {
       template 
       void do_stuff()
        { std::cout << "constexpr case (" << I << ')' << std::endl; }
    
       void do_stuff (std::size_t i)
        { std::cout << "not constexpr case (" << i << ')' << std::endl; }
    
       void execute ()
        {
          if constexpr ( isConstExprEval::value )
             do_stuff();
          else
             do_stuff(base::get_data());
        }
     };
    
    struct foo
     { static constexpr std::size_t get_data () { return 1u; } };
    
    struct bar
     { static std::size_t get_data () { return 2u; } };
    
    int main ()
     { 
       derived{}.execute(); // print "constexpr case (1)"
       derived{}.execute(); // print "not constexpr case (2)"
     }
    

提交回复
热议问题