3

给定一个编译时常量整数(一个对象,而不是一个宏),我可以在编译时将它与字符串文字结合起来,可能与预处理器?组合字符串文字和整数常量

例如,我可以通过把它们彼此相邻的串联字符串文字:

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!"); 

如果这是不可能的,我可以混合常量字符串与字符串文字?即如果我的错误代码是字符串,而不是无符号的?

如果两者都不可能,那么将这些字符串文字和数字错误代码混合在一起的最短,最干净的方法是什么?

回答

9

如果BAD_EOF是一个宏,你可以stringize它:

#define STRINGIZE_DETAIL_(v) #v 
#define STRINGIZE(v) STRINGIZE_DETAIL_(v) 

"My error code is #" STRINGIZE(BAD_EOF) "!" 

但它不是(这只是关于总是一件好事),所以你需要formatthestring

stringf("My error code is #%d!", BAD_EOF) 

stringstream ss; ss << "My error code is #" << BAD_EOF << "!"; 
ss.str() 

如果这是您的一个巨大担忧(不应该,绝对不是),请为每个常量使用单独的专用字符串:

unsigned const BAD_EOF = 1; 
#define BAD_EOF_STR "1" 

这有一个宏的所有缺点加上拧紧 保持一小部分的性能可能won't matter大多数应用程序的性能。但是,如果决定进行这种权衡,则必须是宏,因为预处理器无法访问值,即使它们为常量,也不能访问

+0

啊,是的。这个双重宏观很重要。在我的例子中我忘了一些东西。不错的演出。 – JoshD 2010-10-04 23:51:21

+0

为什么双重宏? – Chubsdad 2010-10-05 00:05:47

+3

@Chubsdad:http://codepad.org/DiAC35hl – 2010-10-05 00:09:10

1

出了什么问题:如果你想抽象的错误代码

do_stuff(my_int_1, 
    my_int_2, 
    "My error code is #1 ! I encountered an unexpected EOF!\n" 
    "This error code is ridiculously long so I am going to split it onto " 
    "three lines!"); 

,那么你可以这样做:

#define BAD_EOF "1" 

然后你可以使用BAD_EOF就好像它是一个字符串。

+1

嗯。如果#define被用作整数类型,这可能会破坏很多代码 – Chubsdad 2010-10-05 02:50:09