"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Can C++ Deduce Template Types from Function Return Types?

Can C++ Deduce Template Types from Function Return Types?

Published on 2024-11-10
Browse:238

Can C   Deduce Template Types from Function Return Types?

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
Latest tutorial More>

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