1

I have two classes: A and B, and an implicit conversion from As to Bs. 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?

Community
  • 1
  • 1
zmbq
  • 38,013
  • 14
  • 101
  • 171
  • 3
    Your link "described here" gives a one line answer to your question. What don't you like about that answer? – Dale Wilson Feb 11 '15 at 22:47
  • This one line makes me describe *how* to make the conversion in my code, not simply that I want to make the conversion. It's too verbose. – zmbq Feb 11 '15 at 23:04

4 Answers4

2

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.

myaut
  • 11,174
  • 2
  • 30
  • 62
1

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() );
}
sp2danny
  • 7,488
  • 3
  • 31
  • 53
1

One class that inherits vector< A > and another class that inherits vector< B > and implement constructor that takes the other class as a parameter.

Tony J
  • 599
  • 5
  • 16
0

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.

zmbq
  • 38,013
  • 14
  • 101
  • 171