[英]Is it possible to create a vector of a template class and call its functions?
我创建了一个模板 class ,其中包含一些用作参数模板类型的方法,如下所示:
template <class T>
class vector{
...
void new(const T&new_value)
...
}
我想在另一个 class 中使用它,但由于不允许这样声明它:
class matrix{
vector *_ptr_to_vect;
}
我创建了一个基础 class BaseVector
。
但是在BaseVector
中,我无法定义像new(const T&new_value)
这样的虚拟 function 来覆盖它(因为我不想再次使用模板)。 由于我无法定义它,所以不可能这样称呼它:
BaseVector _ptr_to_vect;
BaseVector[0].new("new value")
您不需要基础 class。 您需要将matrix
作为模板:
template <class T>
class matrix{
vector<T> _ptr_to_vect;
};
或者,如果您的矩阵 class 始终属于一种类型(例如,假设float
):
class matrix{
vector<float> _ptr_to_vect;
};
作者评论:
问题是我想要一个不同类型的矩阵。 例如整数的第一列,浮点数的第二列等等
在纯 C++11 中,您可能会为此使用一些模板魔术:
//
// Lightweight wrapper over any type
//
template<typename T>
struct identity {
using type = T;
};
//
// Metafunction that converts type T
// into vector<T>
//
template<typename T>
struct add_vector {
using type = vector<T>;
};
//
// Function used to obtain std::tuple<vector<Types>>
// type from Types
//
template<typename... Types>
constexpr auto make_tuple_of_vectors()
{
return identity<
std::tuple< add_vector<Types>::type... >
>{};
}
//
// Our matrix, it receives types of all its
// columns as template parameters
//
template<typename... ColumnTypes>
class matrix
{
using matrix_internal_t = decltype(
make_tuple_of_vectors<ColumnTypes...>
)::type;
static constexpr size_t columns_count =
sizeof...( Types );
public:
// Don't know why you need a pointer here
// It's better to store a value maybe
matrix_internal_t* matrix_ptr;
};
此解决方案允许您在不同的列中存储不同的类型。 问题仅在于索引。 您必须在编译时知道要访问的列的索引。
您可以提供以下成员函数:
template<size_t column_index>
auto get_column()
{
static_assert(
column_index < columns_count,
"Out of range"
);
return std::get<column_index>( *matrix_ptr );
}
在通过以下方法获得的每一列中,您可以使用[]
运算符。
用法:
matrix<int, float, double> m;
// Get the first column (with integers)
auto v1 = m.get_column<0>();
// Get the second column (with floats)
auto v2 = m.get_column<1>();
// Get 4'th column, that doesn't exist
// Raises compilation error
// auto v4 = m.get_column<3>();
为了更优雅地访问第 ij 个元素,您可以定义一个宏:
// j must be known at compile-time
#define get_element( matrix, i, j ) matrix.get_column<j>()[i]
对于列的迭代,您可以编写自己的for_each
,但有点复杂:尝试为元组找到for_aech
的实现或自己编写:) 编写这样的算法是一个好习惯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.