你能编写预处理器指令来返回一个 std::string 或 char* 吗?
例如:如果是整数:
#define square(x) (x*x)
int main()
{
int x = square(5);
}
我想做同样的事情,但使用像 switch-case 模式这样的字符串。如果通过 1,它应该返回“一”和“二”的 2,依此类推。
最佳答案
您不想在 C++ 中使用宏来执行此操作;一个功能很好:
char const* num_name(int n, char const* default_=0) {
// you could change the default_ to something else if desired
static char const* names[] = {"Zero", "One", "Two", "..."};
if (0 <= n && n < (sizeof names / sizeof *names)) {
return names[n];
}
return default_;
}
int main() {
cout << num_name(42, "Many") << '\n';
char const* name = num_name(35);
if (!name) { // using the null pointer default_ value as I have above
// name not defined, handle however you like
}
return 0;
}
同样,square 应该是一个函数:
inline int square(int n) {
return n * n;
}
(虽然在实践中平方不是很有用,但您可以直接乘以。)
出于好奇,虽然在这种情况下我不推荐它(上面的函数很好),但模板元编程等效项是:
template<unsigned N> // could also be int if desired
struct NumName {
static char const* name(char const* default_=0) { return default_; }
};
#define G(NUM,NAME) \
template<> struct NumName<NUM> { \
static char const* name(char const* default_=0) { return NAME; } \
};
G(0,"Zero")
G(1,"One")
G(2,"Two")
G(3,"Three")
// ...
#undef G
请注意,TMP 示例失败的主要方式是您必须使用编译时常量而不是任何 int。
关于c++ - 编写预处理器指令以获取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2422843/