如何定义运算符,以便可以将用户定义类型的数组转换为基本类型数组? [英] How can I define operators so that a array of user-defined types can be transformed into an array of primitive types?
问题描述
我给出以下代码来说明我的问题:
I give the following code to illustrate my question:
#include <vector>
struct Complex
{
int a, b, c;
Complex() : a(3), b(4), c(10) {}
operator int() const { return a+b+c; }
};
int main()
{
Complex abc;
int value = (abc);
Complex def;
def.a = 20;
int value2 = (def);
std::vector<Complex> ar;
ar.push_back(abc);
ar.push_back(def);
std::vector<int> ar2;
ar2.push_back(abc);
ar2.push_back(def);
std::vector<int> ar3;
ar3 = (ar);
}
由于表达式 ar3 =(ar)
。我已经声明了一个转换操作符,使得 Complex
类可以在期望 int
的地方使用。我也可以让它工作,将复杂
对象的数组赋给 int
?
This won't compile, due to the expression ar3 = (ar)
. I have declared a conversion operator so that the Complex
class can be used in where int
is expected. Can I also make it work for assigning an array of Complex
objects to an array of int
?
我试图为 Complex
的数组声明一个非成员转换运算符,但不允许:
I tried to declare a non-member conversion operator for array of Complex
, but that's not allowed:
void std::vector<int> operator = (std::vector<Complex> complexArray)
{
std::vector<int> abc;
for(int i=0; i<complexArray.size(); i++)
abc.push_back(complexArray[i]);
return abc;
}
推荐答案
至少对于标准库容器)。但是如果你愿意接受一个显式转换,如下面的例子
Forget about automatic implicit conversion (at least for the Standard Library containers). But if you are willing to accept an explicit conversion like in the below example
const std::vector<int> vi {1, 2, 3, 4, 5};
const std::vector<double> vd = container_cast(vi);
然后执行 container_cast()
效用如下。注意,它不仅可以在不同元素类型的同一模板容器的实例化之间转换(即 std :: vector
到 std :: (例如
std :: vector
到 std :: list )。
then the implementation of the container_cast()
utility follows. Note that it can cast not only between instantiations of the same template container for different element types (i.e. std::vector<int>
to std::vector<double>
), but also between different containers (e.g. std::vector
to std::list
).
#include <iostream>
#include <vector>
#include <list>
template<class SourceContainer>
class ContainerConverter
{
const SourceContainer& s_;
public:
explicit ContainerConverter(const SourceContainer& s) : s_(s) {}
template<class TargetContainer>
operator TargetContainer() const
{
return TargetContainer(s_.begin(), s_.end());
}
};
template<class C>
ContainerConverter<C> container_cast(const C& c)
{
return ContainerConverter<C>(c);
}
template<class C>
void printContainer(const C& c)
{
std::cout << "{ ";
for( auto x : c )
std::cout << x << ' ';
std::cout << "}" << std::endl;
}
int main()
{
const std::vector<double> vd {2.2, 7.7, 5.5, 1.1, -4.4};
printContainer(vd);
const std::vector<int> vi = container_cast(vd);
printContainer(vi);
const std::list<float> lf = container_cast(vd);
printContainer(lf);
return 0;
}
这篇关于如何定义运算符,以便可以将用户定义类型的数组转换为基本类型数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!