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)
for(auto &&i: {args...}) keys.push_back(std::move(i));
Run Code Online (Sandbox Code Playgroud)
(keys.push_back(args), ...);
Run Code Online (Sandbox Code Playgroud)
template<class... Args> Combo(Args... args): keys_{uint8_t(args)...} {}
Run Code Online (Sandbox Code Playgroud)
在使用fold expression 的c++17 中,您可能会这样做
#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)
| 归档时间: |
|
| 查看次数: |
102 次 |
| 最近记录: |