Search code examples
c++templatestemplate-argument-deduction

Template deduction for function based on its return type?


I'd like to be able to use template deduction to achieve the following:

GCPtr<A> ptr1 = GC::Allocate();
GCPtr<B> ptr2 = GC::Allocate();

instead of (what I currently have):

GCPtr<A> ptr1 = GC::Allocate<A>();
GCPtr<B> ptr2 = GC::Allocate<B>();

My current Allocate function looks like this:

class GC
{
public:
    template <typename T>
    static GCPtr<T> Allocate();
};

Would this be possible to knock off the extra <A> and <B>?


Solution

  • 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>