I would like to use decltype to virtually bind the return type of a method to a type of a variable like that
#include <iostream>
decltype(a) foo() // my point
{
return 4.3f;
}
int main(int argc, char* argv[])
{
auto a = 5.5f;
std::cout << foo() << std::endl;
return(0);
}
but this code doesn’t compile under g++-4.7.2 on Linux as you can easily guess.
There is a workaround for this ? I know auto but this is not what i would like to use ( I do not want to use auto for the return type of foo()) .
What exactly is your goal here? Is it ok to pass the variable in to the function? If not, how is the function expected to know what type to use? If you are ok with passing the variable in to the function, you can use a template:
Now you can call it like
The variable here is only being used to get its type. If you don’t want to pass the variable in, then you need to provide the type directly, e.g.
But this is, of course, quite ugly.
Now, if you are willing to use macros, you can simplify this slightly:
but of course this does hard-code the name of the variable that must be in-scope when you call foo().
The fundamental issue here is the function cannot implicitly use the type of the variable, as the function is declared first. So if templates are not a good solution, then the only alternative is to declare the type somewhere that both the function and the variable can access it. This can be accomplished with a
typedef:Alternatively, you can simply decide that the return value of
foo()is considered the authority on the type in question: