How to cast from list<T*> to list<const T*>

A

Alexander Malkis

//Consider:
class A { /*...*/ };

template<class T> class list {/*... */ };

void f(const list<const A*> lst) { /*...doesn't change the arg...*/ }

void g(list<A*> lst) {
f(lst); //Intuitively ok, but compiler rejects.
}

/* Compiler says:
error: conversion from `list<A*>' to non-scalar type `list<const A*>'
requested

Cast doesn't help either. What to do?
*/
 
V

velthuijsen

Alexander Malkis said:
//Consider:
class A { /*...*/ };

template<class T> class list {/*... */ };

void f(const list<const A*> lst) { /*...doesn't change the arg...*/ }

void g(list<A*> lst) {
f(lst); //Intuitively ok, but compiler rejects.
}

/* Compiler says:
error: conversion from `list<A*>' to non-scalar type `list<const A*>'
requested

Cast doesn't help either. What to do?
*/

2 things

1) You are working on a list why not use the STL list(or one of the
other containers)?

2) did you really mean -> void f(const list<const A*> lst)
or did you want to do -> void f(const list<const A*>& lst)
?

That said because you are using a template there are two distinct
classes one is list<A*> and the other is list<const A*> which are in
no way related.
My first guess is that you'd need to write a conversion routine that
accepts a T and converts is to a const T.

My first guess seems to be supported by the compiler I'm using (VC++
7)
The intel compiler spits out the following error:
error: no suitable user-defined conversion from "list<A *>" to "const
list<const A *>" exists f(lst); //Intuitively ok, but compiler
rejects.

The M$ compiler spits out the following error:
error C2664: 'f' : cannot convert parameter 1 from 'list<T>' to 'const
list<T>' with [ T=A * ] and [ T=const A * ]
 
A

Alexander Malkis

velthuijsen said:
1) You are working on a list why not use the STL list(or one of the
other containers)?
I have my own functions for lists which are not present in standard
libraries.
2) did you really mean -> void f(const list<const A*> lst)
or did you want to do -> void f(const list<const A*>& lst)
?
It's not essential for the matter of conversion.
My first guess is that you'd need to write a conversion routine that
accepts a T and converts is to a const T.
You mean maybe (T*) to (const T*) ?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,439
Messages
2,571,700
Members
48,796
Latest member
Greg L.
Top