1

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.

tuzhi
  • 109
  • 8
  • 1
    What are you really trying to do? It looks for me that your macro doesn't do anything useful, that couldn't be done without it already. Also you cannot access particular tuple elements with a runtime index. Rather check `std::initializer_list`. – πάντα ῥεῖ Feb 05 '17 at 03:33
  • I need to use the parameter "a" "b" as a member of a class T like T.a, they cannot be passed as variable. – tuzhi Feb 05 '17 at 04:47
  • That's why I mentioned `std::initializer_list`, also we have variadic template parameters nowadays. – πάντα ῥεῖ Feb 05 '17 at 04:49

2 Answers2

0

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
}
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
0

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

Community
  • 1
  • 1
Guillaume Racicot
  • 39,621
  • 9
  • 77
  • 141