How to ensure constexpr function never called at runtime?

后端 未结 5 1033
无人及你
无人及你 2020-12-05 18:52

Lets say that you have a function which generates some security token for your application, such as some hash salt, or maybe a symetric or asymetric key.

Now lets sa

5条回答
  •  感动是毒
    2020-12-05 19:23

    A theoretical solution (as templates should be Turing complete) - don't use constexpr functions and fall back onto the good-old std=c++0x style of computing using exclusively struct template with values. For example, don't do

    constexpr uintmax_t fact(uint n) {
      return n>1 ? n*fact(n-1) : (n==1 ? 1 : 0);
    }
    

    but

    template  struct fact {
      uintmax_t value=N*fact::value;
    }
    template <> struct fact<1>
      uintmax_t value=1;
    }
    template <> struct fact<0>
      uintmax_t value=0;
    }
    

    The struct approach is guaranteed to be evaluated exclusively at compile time.

    The fact the guys at boost managed to do a compile time parser is a strong signal that, albeit tedious, this approach should be feasible - it's a one-off cost, maybe one can consider it an investment.


    For example:

    to power struct:

    // ***Warning: note the unusual order of (power, base) for the parameters
    // *** due to the default val for the base
    template 
    struct pow_struct
    {
    private:
      static constexpr uintmax_t at_half_pow=pow_struct::value;
    public:
      static constexpr uintmax_t value=
          at_half_pow*at_half_pow*(exponent % 2 ? base : 1)
      ;
    };
    
    // not necessary, but will cut the recursion one step
    template 
    struct pow_struct<1, base>
    {
      static constexpr uintmax_t value=base;
    };
    
    
    template 
    struct pow_struct<0,base>
    {
      static constexpr uintmax_t value=1;
    };
    

    The build token

    template 
    struct build_token {
      constexpr uintmax_t value=
           vmajor*pow_struct<9>::value 
         + vminor*pow_struct<6>::value 
         + build_number
      ;
    }
    

提交回复
热议问题