My question: Say I'm defining a function in C++ (or in C). Is there anything similar to C++'s auto or decltype that I can use inside the function definition in order to declare a local variable with type inferred from the return type of the function that I'm defining?
Example: A common coding pattern in C and C++ is
SomeType foo() {
SomeType x;
// ... do something to x ...
return x;
}
And I'm hoping to infer the second SomeType instead of typing it in explicitly. The following doesn't work, but I was hoping I could do something in this spirit
SomeType foo() {
decltype(return) x; //<-- infer the function return type, which here is SomeType
// ... do something to x ...
return x;
}
For simple return types it's not a big deal, but when return types are complicated (say the return type is a template class with lots of template parameters), it would be nice (and less error-prone) to not have to repeat that type definition inside the function.
I'd also like to not have to change the function definition to accomplish this. So, while in the example above it could work to change SomeType to a macro, or perhaps make foo a template function and SomeType a template parameter, really I'm looking to see if in general I can infer a type specifically from the return type of the surrounding function.
Maybe the answer is "no it's not possible", which is fair, but I'd like to know one way or the other.
It is dangerous to have a dangling pointer like that as pointers or references to local variables are not allowed to escape the function where local variables live; hence, the compiler throws an error.
No you can't, that's what "local" means.
A local variable retains its value until the next time the function is called A local variable becomes undefined after the function call completes The local variable can be used outside the function any time after the function call completes.
You can declare local variables with the same name as a global variable, but the local variable will shadow the global.
In C++11:
SomeType foo()
{
decltype(foo()) x;
The expression foo()
has the same type as the return value of foo
.
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