我想编写一个
table
类,它以多列作为参数来创建表。这是我的尝试。
template <typename T = double>
class table
{
private:
using type = std::remove_reference_t<std::remove_cv_t<T>>;
static_assert(std::is_arithmetic_v<type>);
using coltype = std::vector<type>;
std::vector<coltype> m_data;
public:
template <typename... Args>
table(Args &&...args)
{
static_assert(sizeof...(args) >= 2);
static_assert((std::is_constructible_v<coltype, Args &&> && ...));
(m_data.push_back(std::forward<Args>(args)), ...);
}
~table() = default;
// ... other stuff
};
但是,目前这不适用于大括号括起来的初始值设定项列表。我打算按如下方式使用它:
std::vector<double> vec1{1.,2.,3.};
std::vector<double> vec2{4.,5.,6.};
table t1(vec1,vec2); //works
table t2({1.,2.,3.},{4.,5.,6.}); //doesn't compile as brace-enclosed initializers doesn't have a type
table t3({1,2,3},vec1,vec2) // also possibly combinations
如何实现这一目标?是否可以使用
std::initializer_list
进行一些实施?
您似乎想使用
std::initializer list<T>
。
#include <initializer_list>
#include <vector>
template <typename T = double>
class table {
private:
using type = std::remove_reference_t<std::remove_cv_t<T>>;
static_assert(std::is_arithmetic_v<type>);
using coltype = std::vector<type>;
std::vector<coltype> m_data;
public:
table(std::initializer_list<std::vector<T>> args) { m_data = args; }
~table() = default;
// ... other stuff
};
int main() {
std::vector<double> vec1{1., 2., 3.};
std::vector<double> vec2{4., 5., 6.};
table t1{vec1, vec2}; // works
table t{{1., 2., 3.}, {4., 5., 6.}};
table t3{{1, 2, 3}, vec1, vec2}; // also possibly combinations
}