This topic is now archived and is closed to further replies.


Why does this work? ( C++ templates )

Recommended Posts

While mucking around with coding a variant type variable in c++ I wrote the following piece of code that worked in a somewhat surprising manner:
template <class T>
var_t& operator= ( T* ptr ) {
    u.vptr = static_cast<void*> ptr;
    type = VAR_PTR;
    return *this;

template <class T>
operator T*() {
    if ( type == VAR_PTR ) return static_cast<T*>(u.vptr);
    throw E_INVALID_CAST;
What came as a bit of a surprise to me was that it isn''t necessary to specify T when calling either of these functions. In effect, the following works:
var_t v;
SomeClass sc ( /* constructor details */ );
v = ≻
SomeClass* scptr = v;
// scptr is now a valid MyClass pointer with correct values

Just to clarify, u is a data member of var_t, and is a union of a few different types, including a void* (vptr). Now, I haven''t used templates all that much, but this seems a bit odd. I was under the impression that the correct way to call these functions would be something along the lines of
var_t v;
SomeClass sc ( /* constructor details */ );
v<SomeClass> = ≻
SomeClass* scptr = v<SomeClass>;/* Not sure about this one */
( The line marked "Not sure..." looks very wrong to me when I look at it, but it''s the closest I could think of off the top of my head ). Anybody have any thoughts on how and why this works? -Neophyte P.S. Compiled using gcc 2.96 and run in Red Hat Linux 7.3

Share this post

Link to post
Share on other sites