提取函数的返回类型而不调用它(使用模板?)

pau*_*doo 8 c++ templates metaprogramming c++11

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

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'
Run Code Online (Sandbox Code Playgroud)

我目前正在调查如何magic_template实施,但到目前为止尚未找到解决方案.

有任何想法吗?

Dav*_*eas 7

看看boost 类型特征库,特别是function_traits模板提供了开箱即用的功能.如果你不能使用boost,只需下载代码并阅读源代码,以便深入了解它是如何完成的.

请注意,该功能基于类型,而不是具体功能,因此您可能需要在那里添加一些额外的代码.


在做了一些小测试之后,这可能不是你真正需要的,如果它是'一些额外的代码'将是非平凡的.问题是function_traits模板适用于函数签名而不是实际的函数指针,因此问题已经从"从函数指针获取返回类型"变为"从函数指针获取签名",这可能是最难的部分.


Jam*_*kin 5

它很棘手,因为函数名称不是类型 - 你需要类似gcc的东西typeof.Boost的TypeOf是一种非常接近的便携式解决方案.

但是,如果可以组织代码以便在功能模板内完成工作,Foo或者Bar可以传递,则有一个直截了当的答案:

template <class R>
void test(R (*)())
{
  R var1;
}

int main()
{
  test(&Foo);
}
Run Code Online (Sandbox Code Playgroud)


Joe*_*oeG 5

Foo和Bar是函数,而不是函数类型,因此您需要做一些额外的工作.

这是使用boost :: function_traits和BOOST_TYPEOF组合的解决方案.

#include <boost/typeof/typeof.hpp>
#include <boost/type_traits.hpp>

float Foo();
int Bar();

int main()
{
  boost::function_traits<BOOST_TYPEOF(Foo)>::result_type f = 5.0f;
  boost::function_traits<BOOST_TYPEOF(Bar)>::result_type i = 1;
  return i;
}
Run Code Online (Sandbox Code Playgroud)

编辑:

  • 这适用于任何高达10的arity的功能,这应该足以满足最明智的用途.
  • 这种BOOST_TYPEOF的使用适用于不提供本机类型的平台,因此它具有合理的可移植性.