C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 通过模板传递函数时的推断返回类型大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我的问题是让编译器根据模板传递的函数的返回类型推断函数的返回类型.

有什么方法可以称之为

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,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("%d\n",foo<decltype(bar),bar>(7.3));
}

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

#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 – 通过模板传递函数时的推断返回类型全部内容,希望文章能够帮你解决c – 通过模板传递函数时的推断返回类型所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。