Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can C++ use local variables inside a function whose type is automatically inferred from the function return type?

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.

like image 212
Kevin Holt Avatar asked Aug 13 '14 22:08

Kevin Holt


People also ask

Is it unsafe for a function to return a local variable by reference?

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.

Is it possible for a function to access a variable that is local to another function?

No you can't, that's what "local" means.

What happens to local variables when the function is completed?

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.

Can we declare local two variables in a function with same name but different data type co3?

You can declare local variables with the same name as a global variable, but the local variable will shadow the global.


1 Answers

In C++11:

SomeType foo()
{
    decltype(foo()) x;

The expression foo() has the same type as the return value of foo.

like image 102
M.M Avatar answered Sep 23 '22 14:09

M.M