<os******@gmail .comwrote in message
news:39******** *************** ***********@i36 g2000prf.google groups.com...
: I am implementing a lockless queue, which I don't think the
: std::queue<T*pr ovides. To avoid template-induced code bloat, I am
: implementing a generic the queue using void* pointers. But to gain
: type-safety, I am implementing a templated interface-class.
This is a common optimization technique indeed (used back in early
C++ times). But keep in mind that, nowadays, some compilers/linkers
are able to automatically eliminate redundant copies of the same
code, such as those resulting from multiple template instantiations.
: Now what is confusing me is that this function works
:
:
: SpecialQueue::P ush(T* ptr) { GenericQueue::P ush(ptr); }
:
: and it converts T* to void* no problem.
Indeed: the compiler passes a *copy* of ptr to the generic function.
During this copy, it can make an implicit conversion from T* to void*.
: But when I do
:
: SpecialQueue::P op(T*& refPtr) { GenericQueue::P op(refPtr); }
....
: It gives me this error:
:
: "cannot convert parameter 1 from 'int *' to 'void *&'"
Mind the fact that the int* and void* may have different
in-memory representations (even though this is not the case
on the common processor architectures that you and I use).
You can force the behavior you are looking for by using an
explicit cast:
SpecialQueue::P op(T*& refPtr)
{ GenericQueue::P op(reinterpret_ cast<void*&>(re fPtr)); }
However, this will result in undefined behavior, even though
problems will only happen in "exotic" platforms. It will work
perfectly fine on most architectures, but is not portable.
In proper and portable C++, you would need to write:
bool SpecialQueue::P op(T*& refPtr)
{
void * ptr; // I assume this is an output-only parameter
bool const result = GenericQueue::P op(&ptr);
refPtr = static_cast<T*> (ptr); // ok, works if the
// previously pushed pointer was indeed a T* or NULL
// ( any T* can be converted to void* and then back )
return result;
}
As you see, C++ only allows the implicit conversions that are safe.
(except for those (many) that were inherited from C...)
Cheers -Ivan
--
http://ivan.vecerina.com/contact/?subject=NG_POST <- email contact form
Brainbench MVP for C++ <
http://www.brainbench.com