gpt4 book ai didi

c++ - 通过模板传递函数时推断的返回类型

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:18:35 26 4
gpt4 key购买 nike

我的问题是让编译器根据模板传递的函数的返回类型推断函数的返回类型。

有什么方法可以调用吗

foo<bar>(7.3)

代替

foo<double, int, bar>(7.3)

在这个例子中:

#include <cstdio>
template <class T, class V, V (*func)(T)>
V foo(T t) { return func(t); }

int bar(double j) { return (int)(j + 1); }

int main() {
printf("%d\n", foo<double, int, bar>(7.3));
}

最佳答案

如果你想将 bar 保留为 template 参数,恐怕你只能接近它:

#include <cstdio>

template<typename T>
struct traits { };

template<typename R, typename A>
struct traits<R(A)>
{
typedef R ret_type;
typedef A arg_type;
};

template <typename F, F* func>
typename traits<F>::ret_type foo(typename traits<F>::arg_type t)
{ return func(t); }

int bar(double j) { return (int)(j + 1); }

int main()
{
printf("%d\n", foo<decltype(bar), bar>(7.3));
}

如果你想避免重复 bar 的名字,你也可以定义一个宏:

#define FXN_ARG(f) decltype(f), f

int main()
{
printf("%d\n", foo<FXN_ARG(bar)>(7.3));
}

或者,您可以让 bar 成为一个函数 参数,这可以让您的生活更轻松:

#include <cstdio>

template<typename T>
struct traits { };

template<typename R, typename A>
struct traits<R(A)>
{
typedef R ret_type;
typedef A arg_type;
};

template<typename R, typename A>
struct traits<R(*)(A)>
{
typedef R ret_type;
typedef A arg_type;
};

template <typename F>
typename traits<F>::ret_type foo(F f, typename traits<F>::arg_type t)
{ return f(t); }

int bar(double j) { return (int)(j + 1); }

int main()
{
printf("%d\n", foo(bar, 7.3));
}

关于c++ - 通过模板传递函数时推断的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15190605/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com