Sapphire_Brick
Sapphire_Brick

Reputation: 1682

Is there a way to get the values in a parameter pack without using recursion?

I've seen many example codes that use recursion to extract the values from a parameter pack. Is there any way, other than recursion, to extract the values from a parameter pack?

Upvotes: 0

Views: 840

Answers (3)

Sapphire_Brick
Sapphire_Brick

Reputation: 1682

It turns out that it there's a workaround. C++ parameter pack expansions can be used as for each loops:

#include <iostream>

template <int ... ints>
constexpr int product() {
    int ret = 1;
    auto _ = {
        ([&](int i) -> int {
            ret *= i;
            return i;
        })(ints)...
    };
    return ret;
}

int main() {
    std::cout << product<2, 6, 3>() << '\n';
    return 0;
}

The problems are:

  • the above code only works for non-type template parameter packs.
  • there is no break or continue

Edit

Apparently, it's legal to have a goto within a lambda within a parameter pack expansion. (I wasn't aware of this because Clang has a bug that restricts `goto` operands). Nevertheless, it's not a good idea, because it doesn't "clean up" before leaving the lambda.

Upvotes: 1

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29985

Depending on what you want to do, you can use C++17 fold expressions:

template <int ... ints>
constexpr int product() {
    return (ints * ...);
}

Upvotes: 1

rafix07
rafix07

Reputation: 20936

You can forward all pack parameters as a tuple, then call get<0>:

template<class ... Args>
void foo(Args&& ... args) {
    auto&& first = std::get<0>(std::forward_as_tuple(std::forward<Args>(args)...));
}

Upvotes: 1

Related Questions