Afficher un message
Vieux 08/06/2008, 21h41   #2
Frank Birbacher
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: Is this void* cast safe?

Hi!

jason.cipriani@gmail.com schrieb:
> // 'A' is just a run-of-the-mill template class.
> template <class T> class A {
> public:
> void doit () {
> std::printf("A<%s>::doit()\n", typeid(T).name());
> }
> };


and

> void B::call_doit () {
>
> if (t_ == tInt)
> call_doit_er<int>();
> else if (t_ == tFloat)
> call_doit_er<float>();
> else
> assert(0);
>
> }


This looks like a manual virtual function dispatch. I suggest you create
a base class for all A<T> which has a virtual destructor and an abstract
doit() function.


> 1. There's nothing weird going on here with that cast, right?
> Everything should work out OK?


Yes, all is ok.

> 2. In B's destructor, will that destroy the A<T> appropriately?


Yes, correct dtor.

> 3. Is static_cast<> what I want to be using here (as opposed to
> reinterpret_cast, I guess)?


Yes, use static_cast.

> Again maybe this is a silly question but I've been confusing the heck
> out of myself staring at this code all day.


How about:

struct BaseDoIt
{
virtual ~BaseDoIt() {}
virtual void doit() =0;
};

//copied from your code, but BaseDoIt added:
template <class T> class A : BaseDoIt {
public:
void doit () {
std::printf("A<%s>::doit()\n", typeid(T).name());
}
};

// non template class
struct B
{
// but template ctor:
template<typename T>
B();
void call_doit();
private:
const std::auto_ptr<BaseDoIt> er;
};

template<typename T>
B::B()
: er(new A<T>())
{
}

void B::call_doit()
{
er->doit();
}

This is even safer. And cleaner! And faster!

Frank
  Réponse avec citation
 
Page generated in 0,05273 seconds with 9 queries