[英]Is it possible to use function return type as an argument in declaration of another function in C++?
I want something like this: 我想要这样的东西:
std::tuple<int, bool, double> MyFunction_1 (void);
void MyFunction_2 (decltype (MyFunction_1) ¶ms);
Obviously, in this example a code pointer to function would be passed. 显然,在这个例子中,将传递一个代码指向函数的指针。
I want to have the equivalent of this: 我想要相当于这个:
void MyFunction_2 (std::tuple<int, bool, double> ¶ms);
Is it possible to do so? 有可能这样做吗?
decltype (MyFunction_1)
will give you the type of MyFunction_1
(ie the function type std::tuple<int, bool, double> ()
), you need to emulate a function calling 1 (via adding ()
) to get the return type (ie std::tuple<int, bool, double>
), eg decltype (MyFunction_1)
将为您提供MyFunction_1
的类型(即函数类型std::tuple<int, bool, double> ()
),您需要模拟调用 1 的函数 (通过adds ()
)来获取返回类型(例如, std::tuple<int, bool, double>
)
void MyFunction_2 (decltype (MyFunction_1()) ¶ms);
// ^^
1 The expression is evaluated at compile-time, the function won't be called at run-time actually. 1表达式在编译时计算,实际上不会在运行时调用该函数。
The type of MyFunction_1
is not std::tuple<int, bool, double>
- informally you can think of it as a function pointer. MyFunction_1
的类型不是std::tuple<int, bool, double>
- 非正式地,您可以将其视为函数指针。 In fact &MyFunction_1
decays to itself and is certainly a pointer. 事实上,
&MyFunction_1
衰弱了自己, 当然是一个指针。
So decltype(MyFunction_1)
is not what you want. 所以
decltype(MyFunction_1)
不是你想要的。
The solution is to write decltype(MyFunction_1())
. 解决方案是编写
decltype(MyFunction_1())
。 The type of MyFunction_1()
is std::tuple<int, bool, double>
. MyFunction_1()
的类型 是 std::tuple<int, bool, double>
。 Note that this doesn't actually call the function; 请注意,这实际上并不调用该函数; it's rather like
sizeof
in that respect. 在这方面,它更像是
sizeof
。
using RetType = std::invoke_result<decltype(f)>::type;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.