Template deduction for function based on its return type?

That cannot be done. The return type does not take part in type deduction, it is rather a result of having already matched the appropriate template signature. You can, nevertheless, hide it from most uses as:

// helper
template <typename T>
void Allocate( GCPtr<T>& p ) {
   p = GC::Allocate<T>();
}

int main()
{
   GCPtr<A> p = 0;
   Allocate(p);
}

Whether that syntax is actually any better or worse than the initial GCPtr<A> p = GC::Allocate<A>() is another question.

P.S. c++11 will allow you to skip one of the type declarations:

auto p = GC::Allocate<A>();   // p is of type GCPtr<A>

Leave a Comment