How to concatenate static strings at compile time?

丶灬走出姿态 提交于 2019-12-06 22:27:51

问题


I am trying to use templates to create an analogue of the type_info::name() function which emits the const-qualified name. E.g. typeid(bool const).name() is "bool" but I want to see "bool const". So for generic types I define:

template<class T> struct type_name { static char const *const _; };

template<class T> char const *const type_name<T>::_ = "type unknown";

char const *const type_name<bool>::_ = "bool";
char const *const type_name<int>::_ = "int";
//etc.

Then type_name<bool>::_ is "bool". For non-const types obviously I could add a separate definition for each type, so char const *const type_name<bool const>::_ = "bool const"; etc. But I thought I would try a partial specialization and a concatenation macro to derive in one line the const-qualified name for any type which has its non-const-qualified name previously defined. So

#define CAT(A, B) A B

template<class T> char const *const type_name<T const>::_
    = CAT(type_name<T>::_, " const"); // line [1]

But then type_name<bool const>::_ gives me error C2143: syntax error: missing ';' before 'string' for line [1]. I think that type_name<bool>::_ is a static string known at compile time, so how do I get it concatenated with " const" at compile time?

I tried more simple example but same problem:

char str1[4] = "int";
char *str2 = MYCAT(str1, " const");

来源:https://stackoverflow.com/questions/38955940/how-to-concatenate-static-strings-at-compile-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!