PREMISE:
After playing around with variadic templates a little bit, I realized that achieving anything which goes slightly beyond the trivial meta-programming tasks soon becomes pretty cumbersome. In particular, I found myself wishing for a way to perform generic operations over an argument pack such as iterate, split, loop in a std::for_each
-like fashion, and so on.
After watching this lecture by Andrei Alexandrescu from C++ and Beyond 2012 on the desirability of static if
into C++ (a construct borrowed from the D Programming Language) I had the feeling that some sort of static for
would come handy as well - and I feel more of these static
constructs could bring benefit.
So I started wondering if there is a way to achieve something like this for argument packs of a variadic template function (pseudo-code):
template<typename... Ts>
void my_function(Ts&&... args)
{
static for (int i = 0; i < sizeof...(args); i++) // PSEUDO-CODE!
{
foo(nth_value_of<i>(args));
}
}
Which would get translated at compile-time into something like this:
template<typename... Ts>
void my_function(Ts&&... args)
{
foo(nth_value_of<0>(args));
foo(nth_value_of<1>(args));
// ...
foo(nth_value_of<sizeof...(args) - 1>(args));
}
In principle, static_for
would allow for even more elaborate processing:
template<typename... Ts>
void foo(Ts&&... args)
{
constexpr s = sizeof...(args);
static for (int i = 0; i < s / 2; i++)
{
// Do something
foo(nth_value_of<i>(args));
}
static for (int i = s / 2; i < s; i++)
{
// Do something different
bar(nth_value_of<i>(args));
}
}
Or for a more expressive idiom like this one:
template<typename... Ts>
void foo(Ts&&... args)
{
static for_each (auto&& x : args)
{
foo(x);
}
}
RELATED WORK:
I did some search on the Web and found out that something does indeed exist:
QUESTION:
Is there a relatively simple way, possibly through some template meta-programming, to achieve what I am looking for without incurring in the limitations of the existing approaches?