将double和std :: vector< double>协变 [英] Making double and std::vector<double> covariant
问题描述
我正在尝试为任何"数据类型创建包装器,以使它们具有称为 IValue
的通用接口,因此可以在任意类型上调用 get()
具体值并返回具体数据类型的值.在最简单的情况下,我只想能够在 double
和 std :: vector< double>
上调用 get()
.以我的理解,这些数据类型需要是协变的(在我的代码中根本没有).以下是我对代码的原始想象力:
I am trying to make a wrapper for "any" data type such that they have common interface called IValue
so it will be possible to call get()
on any concrete Value and return the value of concrete data type. In simplest case I just want to be able to call get()
on double
and std::vector<double>
. In my understanding these data types need to be covariant (which it is not at all in my code). The following is my raw imagination of the code:
//template<typename T>
class IValue
{
protected:
// typedef std::variant<T, std::vector<T>> return_type; <- this was an approach
public:
IValue() {}
virtual int size() = 0;
virtual /*some special type*/ get() = 0;
};
template<typename T>
class Scalar : public IValue<T> {
T data = NULL;
public:
Scalar(T new_data) : data(new_data) {}
T get() { return data; }
int size() { return 1; }
};
template<typename T>
class Vector : public IValue<T>
{
std::vector<T> data;
public:
Vector(std::vector<T> new_data) : data(new_data) {}
std::vector<T> get() { return data; }
T get_element(int index) { return data[index]; }
int size() { return data.size(); }
};
我在VS17上使用c ++ 17.
I am using c++17 on VS17.
推荐答案
您确实快到了. std :: variant< T,std :: vector< T>>
确实是正确的返回类型,并且您的 get(){返回数据;}
实现也是正确的.从字面上看,唯一的大问题是所有 get
替代的返回类型应为 std :: variant< T,std :: vector< T>>
.
You're indeed almost there. std::variant<T, std::vector<T>>
is indeed the correct return type, and your get() { return data; }
implementations are also correct. Literally the only big problem is that the return type of all get
overrides should be std::variant<T, std::vector<T>>
.
在样式上, get
应该是 const
,添加 override
有助于改善错误消息.
Stylewise, get
should be const
and adding override
helps to improve error messages.
这篇关于将double和std :: vector< double>协变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!