加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:03:39 所属栏目:百科 来源:网络整理
导读:我的问题是让编译器根据模板传递的函数的返回类型推断函数的返回类型. 有什么方法可以称之为 foobar(7.3) 代替 foodouble,int,bar(7.3) 在这个例子中: #include cstdiotemplate class T,class V,V (*func)(T)V foo(T t) { return func(t); }int bar(double
我的问题是让编译器根据模板传递的函数的返回类型推断函数的返回类型.

有什么方法可以称之为

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("%dn",foo<double,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 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("%dn",foo<decltype(bar),bar>(7.3));
}

如果要避免重复条形图名称,也可以定义宏:

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

int main()
{
    printf("%dn",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("%dn",foo(bar,7.3));
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读