我寫了(並使用)我自己的字符串格式化函數,我想簡化功能的使用,具體方式如下所示,但我不確定如何。如何簡化此功能的調用?
下面是相關代碼:
// Object that can hold a copy of every type I want to print.
// Stores the copy in a union, with an enumeration to identify
// the type. any uses C++ constructors, but could also be implemented
// with C99 designated initializers, like so: https://ideone.com/ElQgBV
struct any
{
...
}
// The string format function requires the variable arguments
// to all be of the 'any' type for type safety and (essential for
// my purposes) positional printing.
// Arguments are accessed with a va_list, so essentially
// the variable arguments are treated as an array of any objects.
char* format_function_(const char* fmt, ...);
// I call the above function with this macro that expands the
// variable arguments and adds a default-constructed sentinel
// at the end. The sentinel is used by the function to count
// how many arguments were passed.
#define format(fmt, ...) format_function_(fmt, __VA_ARGS__, any())
// Calling the function like so, via the above macro...
char* str = format("bits:%4b string:%1 %0 int:%3h float:%2.2\n",
any("world"), any("hello"), any(3.14159f), any(42), any((u8)(1<<4)));
// ...returns this string:
// bits:00010000 string:hello world int:0000002A float:3.14
我希望能夠調用像普通*printf
風格函數的函數...
char* str = format("bits:%4b string:%1 %0 int:%3h float:%2.2\n",
"world", "hello", 3.14159f, 42, (u8)(1<<4));
...與利用可能隱藏在另一個宏的後面。
我該如何做到這一點?
編輯/更新位置參數對我的目的是必不可少的。任何不保留此功能的答案都不是有效答案。
既然您已爲問題C++,我建議你看看[模板參數包(HTTP: //en.cppreference.com/w/cpp/language/parameter_pack)。 –
[va_arg](http://linux.die.net/man/3/va_arg) – kaylum
@AlanAu'format_function _()'已經使用了va_list/va_arg /等等。參數在'any'對象中'包裝'爲了類型安全(和其他原因)。我已經更新了這個問題以包含這些信息。 –