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);
}
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
?
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
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>
tostd::vector<double>
), but also between different containers (e.g.std::vector
tostd::list
).You may consider the range constructor of
std::vector
.Whenever you want to transform something, the
std::transform
function might be good to use.In your case you could do something like
After the
std::transform
call above (once you complete it with the code to actually do the structure transformation) the vectorabc
will contain all the converted integers from theComplex
structures in the source vectorcomplexVector
.