static_cast vs. C-stype cast

  • Thread starter Alexander Stippler
  • Start date
A

Alexander Stippler

In some situations I can apply a C-style cast,
but no static_cast. I'm not quite sure about the
differences in such places. A little example:

template <typename T>
class Dummy {
public:
Dummy(int i) {}
};

template <typename T>
void dummy(const Dummy<T> &a) {}

int
main()
{
int i=6;
// a traditional cast works ...
dummy((const Dummy<int> &)i);

// but the static_cast is an invalid type conversion.
dummy(static_cast<const Dummy<int> &>(i));
return 0;
}


I know, that a static_cast to Dummy<int> would have worked in the second
call, but what's the difference between the two casts in the main() above?

regards,
alex
 
C

Chris \( Val \)

[snip]

| int
| main()
| {
| int i=6;
| // a traditional cast works ...
| dummy((const Dummy<int> &)i);
|
| // but the static_cast is an invalid type conversion.
| dummy(static_cast<const Dummy<int> &>(i));
| return 0;
| }
|
|
| I know, that a static_cast to Dummy<int> would have worked in the second
| call, but what's the difference between the two casts in the main() above?

Are you sure you didn't want the following instead ?:

dummy( ( const Dummy<int> ) i );
dummy( static_cast<const Dummy<int> >( i ) );

Cheers.
Chris Val
 
H

Hendrik Schober

Alexander Stippler said:
In some situations I can apply a C-style cast,
but no static_cast. I'm not quite sure about the
differences in such places. A little example:

template <typename T>
class Dummy {
public:
Dummy(int i) {}
};

template <typename T>
void dummy(const Dummy<T> &a) {}

int
main()
{
int i=6;
// a traditional cast works ...
dummy((const Dummy<int> &)i);

// but the static_cast is an invalid type conversion.
dummy(static_cast<const Dummy<int> &>(i));
return 0;
}


I know, that a static_cast to Dummy<int> would have worked in the second
call, but what's the difference between the two casts in the main() above?

I'm not sure. Maybe it's considered to be
two casts: 'int' ==> 'Dummy' and then
casting the temporary to a const reference?
BTW, what's so bad about
dummy( Dummy<int>(i) )
? I think this
dummy<int>( i );

should work as well.
regards,
alex


Schobi

--
(e-mail address removed) is never read
I'm Schobi at suespammers dot org

"Sometimes compilers are so much more reasonable than people."
Scott Meyers
 

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

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,816
Latest member
SapanaCarpetStudio

Latest Threads

Top