[英]Recursive preprocessor macro for strings
我有一些代碼需要大部分的Unicode字符串,但我想讓它有條件(即TEXT("string")
擴展為L"string"
或"string"
,具體取決於設置)。 對於這些,我使用宏:
#ifdef _UNICODE
# define VSTR(str) L##str
#else
# define VSTR(str) str
#endif
與此相關的主要復雜因素是printf格式字符串,它們分別使用%s
和%S
表示相同編碼和其他編碼字符串。 一些字符串來自類似的條件API( TCHAR
和類似的),而一些來自set API(主要是C-string)。 當使用_tprintf
和family時,使用的函數可能會有所不同,使%s
和%S
有條件,並且可能需要翻轉它們。 為了解決這個問題,我將宏定義為適當的格式元素:
#ifdef _UNICODE
# define VPFCSTR(str) "%S"
# define VPFWSTR(str) "%s"
# define VPFTSTR(str) VPFWSTR(str)
#else
# define VPFCSTR(str) "%s"
# define VPFWSTR(str) "%S"
# define VPFTSTR(str) VPFCSTR(str)
#else
現在,這一切都很好,但強制語法:
VSTR("Beginning of a format string, with a string '") VPFTSTR VSTR("' included.")
我希望能夠使用如下語法:
VSTR("Beginning of a format string, with a string '", VPFTSTR, "' included.")
對於Unicode,這需要擴展為:
L"Beginning of a format string, with a string '" L"%s" L"' included."
唯一的復雜因素是可變數量的參數,所有這些參數都需要以相同的方式進行轉換(如果需要,逐個轉換)。
我的第一個想法是使用__VA_ARGS__
來處理這個問題,使用空參數,例如:
VASTR(str, ...) VSTR(str) VASTR(__VA_ARGS__)
不幸的是,由於宏不能在他們自己的定義中使用,因此失敗了。 然后我嘗試了代理:
VASTR2(...) VASTR(__VA_ARGS__)
VASTR(str, ...) VSTR(str) VASTR2(__VA_ARGS__)
代理方法似乎也不起作用。
有沒有辦法處理在(nother)宏的每個參數上運行相同的宏,這需要可變數量的參數? 或者,如果沒有,是否有相同的? 如果是編譯器特定的,MSVC10是首選,但任何東西都是有意義的。
在C / C ++中無法進行遞歸宏擴展。
不確定,但C ++ 0x允許您省略字符串文字串聯的編碼前綴。 因此,您可以嘗試將宏設計為僅將L
到第一個字符串文字並按如下方式使用它:
VSTR("Beginning of a format string, with a string '" VPFTSTR "' included.")
如果我錯了,請糾正我。
類似的Unicode相關問題: 當存在修飾符(L,u8等)時,相鄰字符串文字串聯會發生什么?
使用Boost.Preprocessor庫和這些附加宏,您可以將VSTR宏應用於每個參數:
//Your VSTR macro for one argument
#define VSTR_EACH(str) ...
/**
* PP_NARGS returns the number of args in __VA_ARGS__
*/
#define PP_NARGS(...) \
PP_DETAIL_NARG((__VA_ARGS__,PP_DETAIL_RSEQ_N()))
#define PP_DETAIL_NARG(args) \
PP_DETAIL_ARG_N args
#define PP_DETAIL_ARG_N( \
_1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
_11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
_21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
_31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
_41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
_51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
_61,_62,_63,N,...) N
#define PP_DETAIL_RSEQ_N() \
63,62,61,60, \
59,58,57,56,55,54,53,52,51,50, \
49,48,47,46,45,44,43,42,41,40, \
39,38,37,36,35,34,33,32,31,30, \
29,28,27,26,25,24,23,22,21,20, \
19,18,17,16,15,14,13,12,11,10, \
9,8,7,6,5,4,3,2,1,0
//Convert agruments list to a BOOST_PP_SEQ so we can iterate over it
//This is two macros in order to avoid the bug in MSVC compilers
#define DETAIL_PP_ARGS_TO_SEQ(size, tuple) BOOST_PP_TUPLE_TO_SEQ(size, tuple)
#define PP_ARGS_TO_SEQ(...) DETAIL_PP_ARGS_TO_SEQ(PP_NARGS(__VA_ARGS__), (__VA_ARGS__))
//The macro used inside of BOOST_PP_SEQ_FOR_EACH
#define VSTR_SEQ_EACH(t, data, x) VSTR_EACH(x)
#define VSTR(...) BOOST_PP_SEQ_FOR_EACH(VSTR_SEQ_EACH, ~, PP_ARGS_TO_SEQ(__VA_ARGS__))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.