组合字符串文字和整数常量
给定一个编译时常量整数(一个对象,而不是宏),我可以在编译时将其与字符串文字(可能与预处理器一起使用)结合起来吗?
例如,我可以通过将字符串彼此相邻放置来连接字符串文字:
bool do_stuff(std::string s);
//...
do_stuff("This error code is ridiculously long so I am going to split it onto "
"two lines!");
太棒了!但是,如果我在混合中添加整数常量会怎样:
const unsigned int BAD_EOF = 1;
const unsigned int BAD_FORMAT = 2;
const unsigned int FILE_END = 3;
是否可以使用预处理器以某种方式将其与字符串文字连接起来?
do_stuff("My error code is #" BAD_EOF "! I encountered an unexpected EOF!\n"
"This error code is ridiculously long so I am going to split it onto "
"three lines!");
如果这是不可能的,我可以将常量字符串与字符串文字混合吗?即,如果我的错误代码是字符串,而不是无符号?
如果两者都不可能,那么将字符串文字和数字错误代码组合在一起的最短、最干净的方法是什么?
Given an compile-time constant integer (an object, not a macro), can I combine it with a string literal at compile time, possibly with the preprocessor?
For example, I can concatenate string literals just by placing them adjacent to each other:
bool do_stuff(std::string s);
//...
do_stuff("This error code is ridiculously long so I am going to split it onto "
"two lines!");
Great! But what if I add integer constants in the mix:
const unsigned int BAD_EOF = 1;
const unsigned int BAD_FORMAT = 2;
const unsigned int FILE_END = 3;
Is it possible to use the preprocessor to somehow concatenate this with the string literals?
do_stuff("My error code is #" BAD_EOF "! I encountered an unexpected EOF!\n"
"This error code is ridiculously long so I am going to split it onto "
"three lines!");
If that isn't possible, could I mix constant strings with string literals? I.e. if my error codes were strings, instead of unsigneds?
And if neither is possible, what is the shortest, cleanest way to patch together this mix of string literals and numeric error codes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果 BAD_EOF 是宏,您可以字符串化< /a> 它:
但事实并非如此(这总是一件好事),所以你需要 格式 字符串 :
如果这对您来说是一个巨大的担忧(不应该,绝对不是一开始),请为每个常量使用单独的专用字符串:
这具有宏的所有缺点,还有更多的
搞砸维持一点点性能,这可能并不重要 对于大多数应用程序。但是,如果您决定进行这种权衡,则它必须是宏,因为预处理器无法访问值,即使它们是常量。If BAD_EOF was a macro, you could stringize it:
But it's not (and that's just about always a good thing), so you need to format the string:
If this was a huge concern for you (it shouldn't be, definitely not at first), use a separate, specialized string for each constant:
This has all the drawbacks of a macro plus more to
screwupmaintain for a tiny bit of performance that likely won't matter for most apps. However, if you decide on this trade-off, it has to be a macro because the preprocessor can't access values, even if they're const.有什么问题:
如果你想抽象错误代码,那么你可以这样做:
然后你可以使用 BAD_EOF ,就好像它是一个字符串文字一样。
What's wrong with:
If you want to abstract the error codes, then you can do this:
Then you can use BAD_EOF as if it were a string literal.