Possible to convert list of #defines into strings

前端 未结 8 1101
梦谈多话
梦谈多话 2021-02-05 22:45

Suppose I have a list of #defines in a header file for an external library. These #defines represent error codes returned from functions. I want to wri

8条回答
  •  长情又很酷
    2021-02-05 23:35

    If you definitely want to keep the #define's I would go with Michael's elegant #define STR(code) answer. But defines are more C than C++, and the big downside to defines is you can't put them in a namespace. They will pollute the global namespace of any program you include them in. If it's in your power to change it, I would recommend using an anonymous enum instead:

    enum{ NO_ERROR ONE_KIND_OF_ERROR ANOTHER_KIND_OF_ERROR }
    

    This is exactly the same as the #defines you have, and you can put it in a namespace. And now you can use Michael's other answer involving the static const char* const error_names array yo do what you had originally asked.

提交回复
热议问题