How to stringify an expression in C

前端 未结 7 1348
刺人心
刺人心 2020-12-07 01:53

Is there a way to evaluate an expression before stringification in c?

example:

#define stringify(x)  #x
...
const char * thestring = stringify( 10 *          


        
7条回答
  •  粉色の甜心
    2020-12-07 02:24

    As the other responses have said, this cannot be done with the C preprocessor. This is one of the many shortcomings of C that are solved by C++, This is the sort of thing that can be accomplished in a very elegant manner using Template Metaprogramming.

    To calculate an arithmetic expression at compile time:

    #include 
    namespace mpl = boost::mpl;
    int main(int argc, char *argv[]) {
      const int n = mpl::multiplies, mpl::int_<50> >::value;
      return 0;
    }
    

    Here's a string formatting metafunction I found on the boost mailing list archives. This version will convert an int (like the one calculated above) into a string in a base of your choosing:

    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    #include 
    namespace mpl = boost::mpl;
    struct itoa_ct
    {
      // radix for _itoa() goes up to 36, but only bother with 16 here
      typedef mpl::vector_c radix_t;
      template 
        struct radix_convert
        {
          typedef typename mpl::push_back<
            typename radix_convert::type
            , mpl::char_::type::value>
            >::type type;
        };
      template 
        struct radix_convert
        {
          typedef mpl::string<> type;
        };
      template 
        struct apply
        {
          // All bases != 10 consider I as unsigned
          typedef typename radix_convert<
            Radix, static_cast((Radix == 10 && I < 0) ? -I : I)
            >::type converted_t;
          // Prefix with '-' if negative and base 10
          typedef typename mpl::if_<
            mpl::bool_<(Radix == 10 && I < 0)>
            , mpl::push_front >
            , mpl::identity
            >::type::type type;
        };
    };
    

    Putting the two together your expression becomes:

    const char *thestring = mpl::c_str, mpl::int_<50> >::value>::type>::value;
    

    ... and this all gets turned into nothing more than a constant string "500" at compile time :-)

提交回复
热议问题