Reputation: 39033
I have two classes: A
and B
, and an implicit conversion from A
s to B
s. I also have a vector<A>
, and I want to convert it to vector<B>
. Is it possible to add a conversion that would allow me to implicitly or explicitly convert vector<A>
to vector<B>
?
I know I can use the technique described here, but is there some way to enable an implicit conversion between the two? Or an explicit conversion?
Upvotes: 1
Views: 147
Reputation: 39033
I was hoping for a trick along the line of C#'s along with C++'s template specialization. Something like this:
template<> // C++ specialization
vector<B>::operator vector<A>(this const vector<A> &vec) const // c# extension method
{
return vector<C>(vec.begin(), vec.end());
}
Which would then allow me to simply state:
vector<A> va;
vector<B> vb = va;
Alas, this is not possible in C++, so I'll just add a global function:
vector<B> ConvertToB(const vector<A> &vec);
Thanks, everybody.
Upvotes: 0
Reputation: 651
One class that inherits vector< A > and another class that inherits vector< B > and implement constructor that takes the other class as a parameter.
Upvotes: 1
Reputation: 7687
Indirectly, there is. It might not be what you are looking for,
but you could have your functions be templates that accept
iterator pairs as argument:
void doSomething( const B& );
template<typename Itr>
void foo1( Itr beg, Itr end )
{
while( beg != end )
doSomething(*beg++);
}
void foo2()
{
vector<A> vec;
foo1( vec.begin(), vec.end() );
}
Upvotes: 1
Reputation: 11514
Generally you shouldn't do that, because vector<A>
and vector<B>
have different implementation (especially if vector is a template specialization like vector<bool>
).
If you do not like copying vector, take a look from other perspective: you need that vector<A>
will behave vector<B>
: you need to convert interfaces not implementation. Implementing adapter for vector<A>
with overloaded operator*
and operator->
which would act like B is what you need.
Upvotes: 2