简体   繁体   中英

C++ template | error: parameter packs not expanded with '…':

I'm getting the following error:

error: parameter packs not expanded with '...':
  auto const m = msg...;

code:

#include <cstdio>
#include <iostream>
#include <cstdarg>
#include <string>

using namespace std;

template<typename... T>
void print(T& ... msg)
{
    auto const m = msg...;
    cout << m;
}

int main()
{
    print("a", "o");
}

This syntax:

auto const m = msg...;

is not valid. Try this:

template <typename... T> void print(T &...msg) {
  using var = int[];
  (void)var{0, (std::cout << msg << std::endl, 0)...};
}

Thanks to this reference for being able to answer this question.

If you want to save in a variable, and print, only the last value in msg... pack, maybe

template <typename... T>
void print (T& ... msg)
{
    auto const m = std::get<sizeof...(msg)-1u>(std::tie(msg...));
    std::cout << m;
}

If you want to print all msg... values, starting from C++17 you can use template folding

template <typename... T>
void print (T& ... msg)
{ ((std::cout << msg), ...); }

Before C++17 you could emulate this using the initialization list of an unused variable (see Rohan Bari's answer for a nice example).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM