My question is: Let's say I define a function in C ++ (or in C). Is there something similar to C ++ auto or decltype that I can use inside a function definition to declare a local variable with a type deduced from the return type of the function I Define?
Example: A common coding pattern in C and C ++ -
SomeType foo() { SomeType x; // ... do something to x ... return x; }
And I hope to output the second SomeType instead of typing it explicitly. The following does not work, but I was hoping I could do something like that.
SomeType foo() { decltype(return) x; //<-- infer the function return type, which here is SomeType // ... do something to x ... return x; }
For simple return types, this does not really matter, but when the return types are complex (say, the return type is a template template with many template parameters), it would be nice (and less error prone) to not repeat this type definition inside the function .
I also do not need to change the definition of a function in order to accomplish this. Thus, although in the above example, it can work to change SomeType to a macro, or perhaps make the foo function of the template and SomeType a parameter of the template, really, I want to see if it is possible to deduce the type from the returned type of the surrounding function.
Perhaps the answer is βno, this is impossibleβ, which is true, but I would like to know one way or another.
source share