Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking first parameter from template parameter pack c++

I'm new with templates, specially with parameter pack and I wonder if I can get the first value from the pack.

For example the following code:

template <typename T, typename... Args>
bool register(Args... args) {
    if (!Foo<T>(args..) {
        assert(std::is_same_v<std::string, args...[0]>);
        std::cerr << "Failed call Foo with " + args...[0] + "\n";
    }
}

How do I really get the first value in args...?

Worth to note that args... can contain different types (string, boolean, etc.)

like image 676
Idan Cohen Avatar asked Jun 14 '26 18:06

Idan Cohen


1 Answers

You can use lambda to extract the first parameter:

template<typename T, typename... Args>
bool register(Args... args) {
  if (!Foo<T>(args...)) {
    auto& first = [](auto& first, auto&...) -> auto& { return first; }(args...);
    static_assert(std::is_same_v<std::string,
                                 std::remove_reference_t<decltype(first)>>);
    std::cerr << "Failed call Foo with " + first + "\n";
  }
}
like image 80
康桓瑋 Avatar answered Jun 17 '26 09:06

康桓瑋



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!