In C++, is it possible to get the return type of a function in order to declare a variable without calling that function?

时间:2022-12-20 20:29:05
int myfun()
{
  return 42;
}

I know I can write

我知道我可以写

auto myvar = myfun();

but what if I just want to declare myvar (without using a common typedef)?

但是如果我只想声明myvar(不使用常见的typedef)呢?

the_type_returned_by_myfun myvar;

What can be written instead of the_type_returned_by_myfun?

什么可以写而不是the_type_returned_by_myfun?

3 个解决方案

#1


33  

You can use decltype.

你可以使用decltype。

decltype(myfun()) myvar;
// or
typedef decltype(myfun()) myfun_ret;
myfun_ret myvar2;

And if the function happens to have parameters, you can produce fake parameters with std::declval.

如果函数恰好有参数,则可以使用std :: declval生成伪参数。

#include <utility>

int my_other_fun(foo f);
typedef decltype(myfun(std::declval<foo>())) my_other_fun;

#2


9  

decltype is your friend:

decltype是你的朋友:

decltype(myfun()) myvar;

#3


6  

This is the job of decltype:

这是decltype的工作:

decltype(myfun()) myvar;

#1


33  

You can use decltype.

你可以使用decltype。

decltype(myfun()) myvar;
// or
typedef decltype(myfun()) myfun_ret;
myfun_ret myvar2;

And if the function happens to have parameters, you can produce fake parameters with std::declval.

如果函数恰好有参数,则可以使用std :: declval生成伪参数。

#include <utility>

int my_other_fun(foo f);
typedef decltype(myfun(std::declval<foo>())) my_other_fun;

#2


9  

decltype is your friend:

decltype是你的朋友:

decltype(myfun()) myvar;

#3


6  

This is the job of decltype:

这是decltype的工作:

decltype(myfun()) myvar;