I want to implement like this
#define XX ???
...
std::vector<int> vec;
Func(XX(vec)); --> Func(vec[0], vec[1], ... vec[n-1]);
I don't have any idea how to do this.
Very thanks if you can help me.
CodePudding user response:
Your
Func(vec[0], vec[1], ... vec[n-1])
has a simple problem: if that n
is not known at compile time, how many of those vec[i],
should the compiler generate? In theory, we could think about runtime compilation or pre-generating all the possibilities and then dispatching over them at runtime, but that's both crazy and crazily useless.
So, if n
isn't known beforehand, process your vec[i]
s in a usual manner:
constexpr auto Func(auto&& range) { for (auto&& element: range) /* work */; }
int main() { Func(std::vector{1, 2, 3}); }
However, if n
is a compile-time constant, you can easily get what you want and that Func
is even written for you in the STL:
int main() { apply([](auto&&... elements) { /* work */ }, std::array{1, 2, 3}); }
And, yes, please try to stay away from #define
s: they know nothing about namespace
, constexpr
and other basic C features. Instead, consider sticking to template
- e.g. that's how std::apply
is implemented.
CodePudding user response:
If you provide the n
as a parameter to the macro its possible (though very cludgy) and there are better techniques using templates.
Func(XX(n, vec)); --> Func(vec[0], vec[1], ... vec[n-1]);
#define EXTRACT_15(container) container[14], EXTRACT_14(container)
#define EXTRACT_14(container) container[13], EXTRACT_13(container)
#define EXTRACT_13(container) container[12], EXTRACT_12(container)
#define EXTRACT_12(container) container[11], EXTRACT_11(container)
#define EXTRACT_11(container) container[10], EXTRACT_10(container)
#define EXTRACT_10(container) container[9], EXTRACT_9(container)
#define EXTRACT_9(container) container[8], EXTRACT_8(container)
#define EXTRACT_8(container) container[7], EXTRACT_7(container)
#define EXTRACT_7(container) container[6], EXTRACT_6(container)
#define EXTRACT_6(container) container[5], EXTRACT_5(container)
#define EXTRACT_5(container) container[4], EXTRACT_4(container)
#define EXTRACT_4(container) container[3], EXTRACT_3(container)
#define EXTRACT_3(container) container[2], EXTRACT_2(container)
#define EXTRACT_2(container) container[1], EXTRACT_1(container)
#define EXTRACT_1(container) container[0]
#define EXTRACT_0(container)
#define EXTRACT(size, container) EXTRACT_ ## size(container)
#define XX(size, container) EXTRACT(size, container)
I just noticed that I got that the wrong way around and the EXTRACT_<N>
list the parameters the wrong way around. Which just shows how clunky this is (as it is too much work to fix).