Implement dynamic casts through QueryInterface

RESOLVED INVALID

Status

()

Core
XPCOM
--
enhancement
RESOLVED INVALID
13 years ago
13 years ago

People

(Reporter: Daniel Kraft, Assigned: dougt)

Tracking

Trunk
Points:
---

Firefox Tracking Flags

(Not tracked)

Details

(Reporter)

Description

13 years ago
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:
(Reporter)

Comment 1

13 years ago
If you think this could be used well and there isn't already such a mechanism,
I'll try to implement such a function.

Comment 2

13 years ago
We already have such a templating mechanism, it's called nsCOMPtr<> and 
do_QueryInterface.
Status: UNCONFIRMED → RESOLVED
Last Resolved: 13 years ago
Resolution: --- → INVALID
(Reporter)

Comment 3

13 years ago
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.