如何检索要在模板中使用的函数的返回类型?

Neo*_*ana 9 c++

我有一个函数在某处调用x,返回一个已知值并具有已知参数:

int x(int y);
Run Code Online (Sandbox Code Playgroud)

我还有其他地方,我想创建一个容器来包含n这个函数的调用.然后我想多次执行它.

问题是,我不想依赖它作为int返回类型.我需要在编译时推断出返回类型.就像是:

std::vector<result_of<x(int)>::type> results;
Run Code Online (Sandbox Code Playgroud)

但我不想指定参数值,因为它们是静态的.

Jar*_*d42 6

您可以创建自己的特征,例如:

template <typename F> struct my_result_of;

template <typename F> struct my_result_of<F*> : my_result_of<F> {};

template <typename Ret, typename ... Ts>
struct my_result_of<Ret(Ts...)>
{
    using type = Ret;
};

template <typename F> using my_result_of_t = typename my_result_of<F>::type;
Run Code Online (Sandbox Code Playgroud)

并使用它(假设没有重载x):

std::vector<my_result_of_t<decltype(x)>::type> results;
Run Code Online (Sandbox Code Playgroud)


ere*_*non 5

你很亲密 假设T是调用函数的模板参数:

std::vector<decltype(x(std::declval<T>()))> results;
Run Code Online (Sandbox Code Playgroud)