Variable arguments in C, how to get values with a generic type?

前端 未结 6 1637
花落未央
花落未央 2020-12-01 21:00

I\'m trying to use C stdarg.h lib, with a generic type. The type int, is my generic type > to understand it, please, hold reading. So, my problem is:

I have a functi

6条回答
  •  心在旅途
    2020-12-01 21:43

    To expand on kriss idea

    Since C99, use _Generic to pass to the variadic function pairs of arguments.

    Change the call to use a macro G(obj)

    // test("Hello", "world", 15, 16.000);
    test(G("Hello"), G("world"), G(15), G(16.000), 0);
    

    G is a macro the uses _Generic to distinguish types and provide an enumerator. Then 2 arguments to test are passed: an enumerator to ID the type and then the object itself.

    This obliges _Generic to enumerate many types. There are infinite numbers of possible types, but a basic list _Bool, char, long long, double, char *, etc. is reasonable.

    Then test() uses the enumeration to steer selection of the next argument. Recommend a 0 to end the list.


    A more complete example:
    Formatted print without the need to specify type matching specifiers using _Generic

提交回复
热议问题