使用函数的返回类型和参数类型作为模板类型

时间:2018-09-25 14:36:00

标签: c++ templates template-meta-programming

是否可以找出函数的返回类型和参数类型并将其用作模板类型?考虑以下示例:

template <typename ret, typename in>
class Bar {
  // Some code
}

int foo(float x) {
  return 0;
}

int main() {
  Bar<int, float> b; // Can this be done automatically by inspection of foo at compile time?
}

我可以使用foo的函数签名来设置Bar的模板类型吗?

2 个答案:

答案 0 :(得分:5)

Yessir。

template <class Function>
struct BarFor_;

template <class Ret, class In>
struct BarFor_<Ret(*)(In)> {
    using type = Bar<Ret, In>;
};

template <auto function>
using BarFor = typename BarFor_<decltype(function)>::type;

现在您可以通过以下方式获取您的类型:

 BarFor<foo> b;

See it live on Coliru

答案 1 :(得分:1)

据我所知,您可以获得函数的返回类型,但无法获得函数参数的类型(至少以您现在正在执行的方式)。

这是推断函数的返回类型的方法:

Bar<decltype(foo(1.0)), float> b;

但是,您需要将参数传递给foo函数,我认为这不是您想要的。