Closed Bug 278611 Opened 20 years ago Closed 20 years ago

Implement dynamic casts through QueryInterface

Categories

(Core :: XPCOM, enhancement)

enhancement
Not set
normal

Tracking

()

RESOLVED INVALID

People

(Reporter: domob, Assigned: dougt)

Details

User-Agent:       Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8a6) Gecko/20041227
Build Identifier: Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.8a6) Gecko/20041227

Because dynamic_cast<> is not very good portable, a macro like NS_DYNAMIC_CAST
is missing, even if that could be used good instead of many
QueryInterface-calls. As we can't use dynamic casts as the C++ standard
describes them, we could implement them using the QueryInterface-mechanism (e.
g. using a template method nsDynamicCast<castTo>; macro isn't possible because
the target type can't be a pointer (T*) as it would).

Reproducible: Always

Steps to Reproduce:
If you think this could be used well and there isn't already such a mechanism,
I'll try to implement such a function.
We already have such a templating mechanism, it's called nsCOMPtr<> and 
do_QueryInterface.
Status: UNCONFIRMED → RESOLVED
Closed: 20 years ago
Resolution: --- → INVALID
Of course, but if you have to deal with raw pointers (because of calls such as
GetChildNodes, where you get one returned) it would sometimes be superfluous to
declare a nsCOMPtr<> too (and convert it to a raw pointer again for the next
interface call) just because you can't easy QI without.
I know do_QueryInterface and thought of this function to be the base of dynamic
casting.
The problem is that QueryInterface addrefs.  So you need _something_ a la
nsCOMPtr to manage the refcount...
well, such a nsDynamicCast template could do it, like:

template<class T> class nsDynamicCast {
 public:
  nsDynamicCast(nsISupports* p) { CallQueryInterface(p, &mPtr); }
  operator T* { return mPtr; }

  ~nsDynamicCast() { NS_IF_RELEASE(mPtr); }

 private: T* mPtr;
};

of course, this way, it would only be usable as an inline thing, not to store
temporaries.
You need to log in before you can comment on or make changes to this bug.