开发者

Does C++ support variable numbers of parameters to functions?

Like printf?

But I remember that C++ does name mangling with function name and parameter types,

this can deduce that C++ doesn't support variable length parameters...

I just want to make sure, is that the case?

UPDATE

the开发者_开发知识库 discussion should exclude those included by extern "C"


Yes. C++ inherits this from C. You can write:

void f(...);

This function can take any number of arguments of any types. But that is not very C++-style. Programmers usually avoid such coding.

However, there is an exception: in template programming, SFINAE makes use of this a lot. For example, see this (taken from here):

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);
};

This uses test(...) which is a variadic function.


Yes, C++ supports the ellipsis from C, but I strongly advice against using them, since they are in no way type safe.

If you have access to a good C++11 capable compiler with variadic template support, then you should use that instead. If you don't have that, have a look at how boost::format solves those things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜