The modified example does work, and
in fact is what I would recommend, with a bit of clean up. Reference parameters (in general, whether you get the effect via pointers, references or some other way) are a bit smelly; if you have an available return value, you should use it.
So all we need to do is get rid of that second parameter, since it's no longer needed. (This also cleans up the calling code, and eliminates the defensive-coding question of who's responsible for initializing the pointer.) All it does right now is allow the template to be inferred; but we could instead just specify the template type explicitly, and it would be less work than setting up the "out" variable.
Meanwhile, since we are always returning a pointer, we might as well modify the function signature to reflect that - let the template type be the pointed-to type, rather than the returned type. This again simplifies things for the caller.
Oh, and there are much nicer ways to use standard library containers. :)
// By using standard library algorithms, we can avoid explicitly looping:struct matching_name : public binary_function<RegistryEntry, std::string, bool> { bool operator()(const RegistryEntry& x, const std::string& y) { return x.Name == y; }};template <typename T>T* GetWidget(const std::string& name) { // Search the registry for a widget with a matching name. list<int>::iterator entry = find_if(m_Registry.begin(), m_Registry.end(), bind2nd(matching_name(), name)); return (entry == m_Registry.end()) ? 0 : dynamic_cast<T*>(m_pGUI->GetWidget(entry->WidgetLocation));}// We use it like:GUI_ListBox* pListBox = m_pRegister->GetWidget<GUI_ListBox>("List Box 1");
By the way, though, all these pointers in your design make me nervous. Are these levels of indirection really necessary? Can you show why?