提取函数的返回类型而不调用它(使用模板?) [英] Extract the return type of a function without calling it (using templates?)

查看:156
本文介绍了提取函数的返回类型而不调用它(使用模板?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在C ++中寻找一种方法来提取函数的返回类型(不调用它)。我假设这将需要一些模板魔法。

I'm looking for a way in C++ to extract the return type of a function (without calling it). I presume this will require some template magic.

float Foo();
int Bar();

magic_template<Foo>::type var1; // Here 'var1' should be of type 'float'
magic_template<Bar>::type var2; // and 'var2' should be of type 'int'



我目前正在调查 magic_template 可能已经实现,但是到目前为止还没有找到解决方案。

I am currently investigating how magic_template might be implemented, but have not found a solution so far.

任何想法?

推荐答案

查看boost type traits 库,特别是 function_traits 模板提供了开箱即用的功能。如果您无法使用boost,只需下载代码并阅读源代码以了解如何完成。

Take a look at boost type traits library, in particular the function_traits template provides such functionality out of the box. If you cannot use boost, just download the code and read the sources for some insight into how it is done.

请注意,该功能基于类型,而不是具体函数,所以你可能需要在这里添加一些额外的代码。

Note that the functionality is based on types, not concrete functions, so you might need to add some extra code there.

做一些小测试后,这可能不是什么真的需要,如果是一些额外的代码将是不平凡的。问题是 function_traits 模板在函数签名而不是实际的函数指针上工作,所以问题已经从'获取函数指针的返回类型'改为'从函数指针的签名,这可能是最难的部分。

After doing some small tests, this might not be what you really need, and if it is the 'some extra code' will be non-trivial. The problem is that the function_traits template works on function signatures and not actual function pointers, so the problem has changed from 'get the return type from a function pointer' to 'get the signature from a function pointer' which is probably the hardest part there.

这篇关于提取函数的返回类型而不调用它(使用模板?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆