简体   繁体   English

如何使用可变数量的参数获取Macro的值?

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

I try to get every value of arguments in Macro, as follow 我尝试在Macro中获取每个参数值,如下所示

#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. 参数的数量(“a”,“b”,“c”,“d”,“e”)是可变的,我如何遍历该值。

The number of arguments ("a", "b", "c", "d", "e") are variable, how can I traverse the value. 参数的数量(“a”,“b”,“c”,“d”,“e”)是可变的,我如何遍历该值。

It seems using a std::tuple (or a macro encapsulating it) is the wrong approach to do this (whatever you want to do actually). 似乎使用std::tuple (或封装它的宏)是这样做的错误方法(无论你想做什么)。

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::vectorstd::initializer_list ,如

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 要阅读有关我的unpack变量如何工作的更多信息,请阅读: https//stackoverflow.com/a/25683817/2104697

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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