通过模板传递函数时推断的返回类型 [英] Inferred return type when passing function by template
本文介绍了通过模板传递函数时推断的返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是让编译器根据模板传递的函数的返回类型来推断函数的返回类型。
My question is about having the compiler infer the return type of a function based on the return type of a function passed by template.
有没有办法调用为
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));
}
推荐答案
code> bar 作为模板参数,恐怕你只能接近:
If you want to keep bar
as a template argument, I'm afraid you can only get close to that:
#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
的名称:
You could also define a macro if you want to avoid repeating bar
's name:
#define FXN_ARG(f) decltype(f), f
int main()
{
printf("%d\n", foo<FXN_ARG(bar)>(7.3));
}
或者,您可以让 bar
成为一个函数参数,这可以使你的生活更轻松:
Alternatively, you could let bar
become a function argument, which could make your life easier:
#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));
}
这篇关于通过模板传递函数时推断的返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文