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

haz*_*dev 5 c++ templates type-inference function-pointers

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

有什么办法我可以打电话给

foo<bar>(7.3)
Run Code Online (Sandbox Code Playgroud)

代替

foo<double, int, bar>(7.3)
Run Code Online (Sandbox Code Playgroud)

在这个例子中:

#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));
}
Run Code Online (Sandbox Code Playgroud)

And*_*owl 1

如果你想保留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 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));
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

或者,您可以让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));
}
Run Code Online (Sandbox Code Playgroud)