如何将参数列表存储到向量?

rab*_*ors 4 c++ templates constructor stdvector variadic-templates

如何将可变参数构造函数参数存储到向量?

我失败的尝试示例:

class Combo 
{
public:
   template <class... Args>
   Combo(Args... args) 
   {
      // this->keys_.push_back(args...);

      // this->keys_.push_back(args)...;

      // this->keys_.push_back(std::forward<Args>(args...));

      //for (uint8_t arg : args...)
      //  this->keys_.push_back(arg);

      // ???
   }

private:
   std::vector<uint8_t> keys_;
};
Run Code Online (Sandbox Code Playgroud)

bip*_*pll 5

  1. C++11
for(auto &&i: {args...}) keys.push_back(std::move(i));
Run Code Online (Sandbox Code Playgroud)
  1. C++17
(keys.push_back(args), ...);
Run Code Online (Sandbox Code Playgroud)
  1. 哦,对不起,我错过了明显的:
template<class... Args> Combo(Args... args): keys_{uint8_t(args)...} {}
Run Code Online (Sandbox Code Playgroud)

  • 在 C++11 中我们也可以这样做: `int temp[] = { 0, (keys.push_back(args), 0)... }; (void)temp;` 或只是 `keys = {args...};`。 (2认同)

JeJ*_*eJo 5

在使用fold expression 的,您可能会这样做

#include <vector>
#include <utility> // std::forward

class Combo
{
public:
   template <class... Args>
   Combo(Args&&... args) 
   {
      keys_.reserve(sizeof...(Args));  // reserve memory for unwanted reallocation
      (keys_.emplace_back(std::forward<Args>(args)), ...);
   }

private:
   std::vector<uint8_t> keys_;
};
Run Code Online (Sandbox Code Playgroud)

但是,这将允许传递除uint8_t可以隐式转换为 的那些类型之外的类型,隐 uint8_t式转换将发生。

这将不是所需的行为。因此,我建议static_assert如下。

#include <type_traits> // std::is_same_v

template <class... Args>
Combo(Args&&... args)
{
   // to make sure that the args all are of type `uint8_t`
   static_assert((std::is_same_v<uint8_t, Args> && ...), "Args should be uint8_t");

   keys_.reserve(sizeof...(Args));  // reserve some memory for unwanted reallocation
   (keys_.emplace_back(std::forward<Args>(args)), ...);
}
Run Code Online (Sandbox Code Playgroud)

这将为您提供以下错误

Combo obj{ 1, 2, 3, 4.f };
//                  ^^^^ --> float
Run Code Online (Sandbox Code Playgroud)