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>
?
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.
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.
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With