![](/img/trans.png)
[英]Writing a function using a macro with variable number of arguments
[英]How to get the value of Macro with variable number of arguments?
我嘗試在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;
}
參數的數量(“a”,“b”,“c”,“d”,“e”)是可變的,我如何遍歷該值。
參數的數量(“a”,“b”,“c”,“d”,“e”)是可變的,我如何遍歷該值。
似乎使用std::tuple
(或封裝它的宏)是這樣做的錯誤方法(無論你想做什么)。
如果您有相同類型的未知數量的參數,您可以簡單地使用適當的std::vector
和std::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
}
為什么在使用可變參數模板時使用可變參數宏?
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);
}
然后,如果你真的還想使用宏,你可以這樣聲明它:
#define CONFIG_FUNCTION(...) int setValue(){ return setValueImpl(__VA_ARGS__); }
要閱讀有關我的unpack
變量如何工作的更多信息,請閱讀: https : //stackoverflow.com/a/25683817/2104697
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.