Template Deduction Based on Function Return Type in C
In C , it can be desirable to utilize template deduction to simplify code that instantiates generic functions based on the data types of the function's arguments. Consider the following example:
GCPtr ptr1 = GC::Allocate();
GCPtr ptr2 = GC::Allocate();
Instead of specifying the generic type parameters explicitly, the goal is to achieve this deduction using the return type of the GC::Allocate() function. However, C does not allow type deduction based on the return type.
class GC
{
public:
template
static GCPtr Allocate();
};
Despite the return type being generic, the compiler requires the explicit specification of the template type parameters and when instantiating the GC::Allocate() function.
To mitigate this limitation, an auxiliary function can be introduced:
template
void Allocate(GCPtr& p) {
p = GC::Allocate();
}
Using this function, the original goal can be achieved as follows:
GCPtr p;
Allocate(p);
Whether this syntax offers any significant advantage over the explicit type specification is subjective.
Note: In C 11, it is possible to omit one of the type declarations using the auto keyword:
auto p = GC::Allocate(); // p is of type GCPtr
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3