[英]Does C++ support variable numbers of parameters to functions?
喜歡printf
?
但我記得C ++確實用函數名和參數類型命名,
這可以推斷出C ++不支持可變長度參數......
我只是想確定,是這樣的嗎?
UPDATE
討論應排除extern "C"
所包含的內容
是。 C ++從C繼承了這個。你可以寫:
void f(...);
此函數可以采用任何類型的任意數量的參數。 但那不是很C ++風格。 程序員通常會避免這種編碼。
但是,有一個例外:在模板編程中, SFINAE充分利用了這一點。 例如,看到這個(取自這里 ):
template <typename T>
struct has_typedef_type {
// Variables "yes" and "no" are guaranteed to have different sizes,
// specifically sizeof(yes) == 1 and sizeof(no) == 2.
typedef char yes[1];
typedef char no[2];
template <typename C>
static yes& test(typename C::type*);
template <typename>
static no& test(...);
// If the "sizeof" the result of calling test<T>(0)
// would be equal to the sizeof(yes), the first overload worked
// and T has a nested type named type.
static const bool value = sizeof(test<T>(0)) == sizeof(yes);
};
這使用test(...)
,它是一個可變函數。
是的,C ++支持C語言的省略號,但我強烈反對使用它們,因為它們絕不是類型安全的。
如果您可以訪問具有可變參數模板支持的優秀C ++ 11編譯器,那么您應該使用它。 如果你沒有,請看看boost :: format如何解決這些問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.