Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 967
Marlon Avatar asked Apr 10 '10 10:04

Marlon


People also ask

What is template argument deduction?

Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.

What is C++ type deduction?

Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. In C++, the auto keyword(added in C++ 11) is used for automatic type deduction.

Which function is useful when template of template is used?

Explanation: As a template feature allows you to write generic programs. therefore a template function works with any type of data whereas normal function works with the specific types mentioned while writing a program.

What happens when a function is defined as a template?

Function templates are special functions that can operate with generic types. This allows us to create a function template whose functionality can be adapted to more than one type or class without repeating the entire code for each type. In C++ this can be achieved using template parameters.


1 Answers

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> 
like image 196
David Rodríguez - dribeas Avatar answered Sep 28 '22 21:09

David Rodríguez - dribeas