用于对算术表达式

时间:2016-12-15 23:10:30

标签: c++ clang c-preprocessor stringification

是否可以编写一个预处理器宏来对clang中的整数算术表达式的结果进行字符串化?

例如:

#define WIDTH 20
#define HEIGHT 30

int main()
{
    puts("The total area is " INT_TO_STRING(WIDTH*HEIGHT));
}

我知道可以使用其__if_exists内置宏在Visual C ++中进行操作。这是Visual C ++实现:

#define STRINGIZE_(n) #n
#define STRINGIZE(n) STRINGIZE_(n)

template<bool> struct static_if_t;
template<> struct static_if_t<true> {};
#define static_if(c) __if_exists(static_if_t<(c)>)

template<int N> struct Abs { enum { n = N < 0 ? -N : N }; };

#define INT_TO_STRING(value) \
    static_if ((value)<0) {"-"} \
    UINT_TO_STRING(Abs<(value)>::n)

#define UINT_TO_STRING(value) \
    static_if ((value)>=1000000000) {INT_TO_STRING_HELPER((value),1000000000)} \
    static_if ((value)>=100000000)  {INT_TO_STRING_HELPER((value),100000000)} \
    static_if ((value)>=10000000)   {INT_TO_STRING_HELPER((value),10000000)} \
    static_if ((value)>=1000000)    {INT_TO_STRING_HELPER((value),1000000)} \
    static_if ((value)>=100000)     {INT_TO_STRING_HELPER((value),100000)} \
    static_if ((value)>=10000)      {INT_TO_STRING_HELPER((value),10000)} \
    static_if ((value)>=1000)       {INT_TO_STRING_HELPER((value),1000)} \
    static_if ((value)>=100)        {INT_TO_STRING_HELPER((value),100)} \
    static_if ((value)>=10)         {INT_TO_STRING_HELPER((value),10)} \
                                     INT_TO_STRING_HELPER((value),1)

#define INT_TO_STRING_HELPER(value,place) \
    static_if ((value)/place%10==0) {"0"} \
    static_if ((value)/place%10==1) {"1"} \
    static_if ((value)/place%10==2) {"2"} \
    static_if ((value)/place%10==3) {"3"} \
    static_if ((value)/place%10==4) {"4"} \
    static_if ((value)/place%10==5) {"5"} \
    static_if ((value)/place%10==6) {"6"} \
    static_if ((value)/place%10==7) {"7"} \
    static_if ((value)/place%10==8) {"8"} \
    static_if ((value)/place%10==9) {"9"}

可以用clang完成吗?

0 个答案:

没有答案
相关问题