简体   繁体   中英

How to get the value of Macro with variable number of arguments?

I try to get every value of arguments in Macro, as follow

#include <iostream>
#include <stdio.h>
#include <tuple>
using namespace std;

class T {
public:
    string a;
    string b;
};

#define CONFIG_FUNCTION(...) int SetValue(T t){\
    int arg_len = tuple_size<decltype(make_tuple(__VA_ARGS__))>::value;\
    auto t = make_tuple(__VA_ARGS__);\
    int i = 0;\
    cout << arg_len << endl;\
    while (i < arg_len) {\
        // I need to get every value of __VA_ARGS__
        // t.a = "assigntment"
    }\
    cout << get<1>(t) << endl;\
}

CONFIG_FUNCTION("a", "b", "c", "d", "e");

int main()
{
    T t;
    SetValue(t);
    return 0;
}

The number of arguments ("a", "b", "c", "d", "e") are variable, how can I traverse the value.

The number of arguments ("a", "b", "c", "d", "e") are variable, how can I traverse the value.

It seems using a std::tuple (or a macro encapsulating it) is the wrong approach to do this (whatever you want to do actually).

If you have an unknown number of arguments of the same type, you can simply use an appropriate std::vector and a std::initializer_list , like

std::vector<std::string> v1{"a", "b", "c", "d", "e"}; 
for(auto s : v1) {
    // Handle every value contained in v1
}

std::vector<std::string> v2{"a", "b", "c", "d", "e", "f", "g"}; 
for(auto s : v2) {
    // Handle every value contained in v2
}

Why use a variadic macro when you can use variadic template?

template<typename... Args>
int setValueImpl(Args... args){
    constexpr auto arg_len = sizeof...(Args);

    std::cout << arg_len << std::endl;

    int unpack[] = {(static_cast<void>([](auto value){
        // value is equal to each arguments in args
    }(args)), 0)..., 0};

    static_cast<void>(unpack);
}

Then, if you really still want to do use a macro, you can declare it like this:

#define CONFIG_FUNCTION(...) int setValue(){ return setValueImpl(__VA_ARGS__); }

To read more about how my unpack variable works, read this: https://stackoverflow.com/a/25683817/2104697

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM