[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.c++

casting template using const_cast

puru

11/7/2008 2:01:00 PM

I have a template class like below.
template <TInt S> class XYZ
{

}

const XYZ<10> abc; //Instance of the class

How do remove the constantness of abc using const_cast. I mean, I want
the syntax for that. Something like const_cast<XYZ<10>> abc gives
compiler error.
3 Answers

Barry

11/7/2008 2:53:00 PM

0

On 11?7?, ??10?01?, puru <purushotta...@gmail..com> wrote:
> I have a template class like below.
> template <TInt S> class XYZ
> {
>
> }
>
> const XYZ<10> abc; //Instance of the class
>
> How do remove the constantness of abc using const_cast. I mean, I want
> the syntax for that. Something like const_cast<XYZ<10>> abc gives
> compiler error.

const_cast can only do with pointer, reference and pointer to
member(function).

try this

XYZ<10>* p = const_cast<XYZ<10>*>(&abc);

--
Best Regards
Barry

Hendrik Schober

11/8/2008 1:30:00 PM

0

puru wrote:
> I have a template class like below.
> template <TInt S> class XYZ
> {
>
> }
>
> const XYZ<10> abc; //Instance of the class
>
> How do remove the constantness of abc using const_cast. I mean, I want
> the syntax for that. Something like const_cast<XYZ<10>> abc gives
> compiler error.

Besides Barry's point, the '>>' will give the parser
trouble. It interprets it as a right-shift operator.
You have to separate it by whitespace in order to fix
this. This also happens in nested templates. This
std::vector<std::vector<int>>
results in a syntax error, too, while this
std::vector<std::vector<int> >
is fine.
C++0x supposedly fixes this.

Schobi

peter koch

11/8/2008 11:53:00 PM

0

On 7 Nov., 15:01, puru <purushotta...@gmail.com> wrote:
> I have a template class like below.
> template <TInt S> class XYZ
> {
>
> }
>
> const XYZ<10> abc;  //Instance of the class
>
> How do remove the constantness of abc using const_cast. I mean, I want
> the syntax for that. Something like const_cast<XYZ<10>> abc gives
> compiler error.

Others have explained how, but I believe having to cast is a design
error. Instead of casting yourself out of your errors, you should
correct the design, which in the long run is going to save you time
and trouble.

/Peter