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