Variadic macro expanding

ε祈祈猫儿з 提交于 2019-12-11 14:00:27

问题


I want to know that is there any way to call a C VARIADIC MACRO selectively.

First, let me show some code I want to achieve:

#include <stdio.h>

#define _VA_NARGS_IMPL(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define _VA_NARGS(...) _VA_NARGS_IMPL(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1) 
#define binder(count, ...) arg##count(__VA_ARGS__)
#define foo(...) binder(_VA_NARGS(__VA_ARGS__), __VA_ARGS__)
#define arg1(_1) _1
#define arg2(_1, _2) _1, _2
#define arg3(_1, _2, _3) _1, _2, _3

int main()
{
    printf("%d %d %d", foo(11,22,33));
    return 0;
}

I tested it in VC11, GCC4.8 and Clang 3.4 but none of them could compile it as I wanted.

Yes, I want to call a macro by count of its arguments, but macros are expanded to:

foo(...)
binder(count, ...)
arg_VA_NAGS(...)

Isn't there any trick?


EDIT:

I Wrote in more detail about what I really want.

I found some clue from answers and edited my code.

typedef unsigned short ListHeader;

template<typename T>
inline const size_t GetSize(const T& _obj) {return sizeof(T);}

inline const size_t GetSize(const std::string& _str) {return sizeof(ListHeader) + _str.size() + 1;}

inline const size_t GetSize(const std::vector<std::string>& _vec)
{
    size_t total = 0;

    for (auto item : _vec)
    {
        total += GetSize(item);
    }

    return sizeof(ListHeader) + total;
}

template<typename T>
inline const size_t GetSize(const std::vector<T>& _vec)
{
    size_t total = 0;

    for (auto item : _vec)
    {
        total += GetSize<decltype(item)>(item);
    }

    return sizeof(ListHeader) + total;
}

#define VA_NARGS_IMPL(_1,_2,_3,_4,_5,_6,_7,_8,N,...) N
#define VA_NARGS(...) VA_NARGS_IMPL(__VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1)


#define VARARG_IMPL2(base, count, ...) base##count(__VA_ARGS__)
#define VARARG_IMPL(base, count, ...) VARARG_IMPL2(base, count, __VA_ARGS__) 
#define VARARG(base, ...) VARARG_IMPL(base, VA_NARGS(__VA_ARGS__), __VA_ARGS__)



#define SerialSize(...) VARARG(SerialSize, __VA_ARGS__)



#define SerialSize1(_1) \
    const size_t size() {return GetSize(_1);}
#define SerialSize2(_1,_2) \
    const size_t size() {return GetSize(_1) + GetSize(_2);}
#define SerialSize3(_1,_2,_3) \
    const size_t size() {return GetSize(_1) + GetSize(_2) +  GetSize(_3);}
#define SerialSize4(_1,_2,_3,_4) // same implementation except count of arguments: 1..4
#define SerialSize5(_1,_2,_3,_4,_5) // 1...5
#define SerialSize6(_1,_2,_3,_4,_5,_6) //1...6
#define SerialSize7(_1,_2,_3,_4,_5,_6,_7) //1...7
#define SerialSize8(_1,_2,_3,_4,_5,_6,_7,_8) //1..8


// Please don't care about detailed implementation of my Archive class.
// It's not important now I guess..
class Archive
{
public:
    template<typename T>
    Archive& operator, (T& _val) //comma operator for Variadic macro
    {
        if (reading)
            read(&_val);
        else
            write(&_val);

        return *this;
    }

    Archive& out();
    Archive& in();

private:

    template<typename T>
    Archive& read(T&);
    template<typename T>
    Archive& write(T&);
};



class Serializable
{
public:
    Serializable(void) {}
    virtual ~Serializable(void) {}

    virtual const size_t size() = 0;
    virtual void serialize(Archive&) = 0;
    virtual void deserialize(Archive&) = 0;
};


#define SerialFormat(...) \
    SerialSize(__VA_ARGS__) \
    void serialize(Archive& ar)\
    {\
        ar.out() , ##__VA_ARGS__ ;\
    }\
    void deserialize(Archive& ar)\
    {\
        ar.in() , ##__VA_ARGS__ ;\
    }


//usage:
struct Packet_ReqeustLogin
    : public Serializable
{
    std::string name;
    std::string password;

    SerialFormat(name, password);
};

It was tested in Xcode5 and VC11 but It doesn't work in VC11.

VC11's output is like this :

warning C4002: too many actual parameters for macro 'SerialSize1'

What can I do to fix it?


回答1:


The C preprocessor is not the right tool for what you're trying to do (even if you surmount this problem).

Firstly, be sure that you can't solve the problem with C++ templates.

Failing that, it calls for a code generation too: something which takes a specification of your classes in some notation and generates the code with all the serialization stuff.

Here is another thing. You're trying very hard to coax macros into generating a summation with multiple terms:

GetSize(arg1) + GetSize(arg2) + ... + GetSize(argN)

but you're overlooking that you can have an N-ary function which does the same thing:

GetSizes(arg1, arg2, ... , argN);

now, the macro doesn't have to generate multiple function call terms with a + operator in between, but only the comma separated list of args!

You over-complicated things in your original program also. The printf in that program can be achieved simply:

$ gcc -std=c99 -Wall -pedantic test.c
$ ./a.out
1 2 3
$ cat test.c
#include <stdio.h>

#define foo(arg, ...) arg, ##__VA_ARGS__

int main()
{
  printf("%d %d %d\n", foo(1, 2, 3));
  return 0;
}



回答2:


You cannot put a macro invocation in the arguments to binder because it uses the ## operator directly.

binder(_VA_NARGS(__VA_ARGS__), __VA_ARGS__)
#define binder(count, ...) arg##count(__VA_ARGS__)
=> arg##_VA_NARGS(__VA_ARGS__)(__VA_ARGS__)
=> arg_VA_NARGS(__VA_ARGS__)(__VA_ARGS__)

To macro-replace the arguments, use an intermediate macro.

#define binder_impl(count, ...) arg##count(__VA_ARGS__)
#define binder(...) binder_impl( __VA_ARGS__ )

I can't tell what your ultimate goal is, but this bug just jumped out at me.




回答3:


The biggest trick is understanding ## and how __VA_ARGS__ expands. Here is an example that I use for Linux syscalls (number of args -1 , since the first arg refers to the syscall number ... note that it therefore ends with a 0 as opposed to most other examples)

#define MKFNS(fn,...) MKFN_N(fn,##__VA_ARGS__,9,8,7,6,5,4,3,2,1,0)(__VA_ARGS__)
#define MKFN_N(fn, n0, n1, n2, n3, n4, n5, n6, n7, n8, n9, n, ...) fn##n

#define syscall(...) MKFNS(syscall,##__VA_ARGS__)
#define syscall1(n,a) _syscall1(n,(long)(a))
#define syscall2(n,a,b) _syscall2(n,(long)(a),(long)(b))
#define syscall3(n,a,b,c) _syscall3(n,(long)(a),(long)(b),(long)(c))
#define syscall4(n,a,b,c,d) _syscall4(n,(long)(a),(long)(b),(long)(c),(long)(d))
#define syscall5(n,a,b,c,d,e) _syscall5(n,(long)(a),(long)(b),(long)(c),(long)(d),(long)(e))

now I can just define a syscall by: #define open(...) syscall(__NR_open,__VA_ARGS__) and it will expand to syscall3(5,(long)a,(long)b,(long)c) when open is called with 3 parameters (the 5 for __NR_open comes indirectly from #including unistd.h).



来源:https://stackoverflow.com/questions/20039565/variadic-macro-expanding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!