返回std::函数的函数的返回类型

Return type of function that returns an std::function

本文关键字:函数 返回类型 std 返回      更新时间:2023-10-16

我有一个函数,它应该返回一个与该函数类型相同的std::函数。基本上我想要这样的东西:

using RetType = std::function<RetType(void)>;

这显然不会编译。如何正确声明返回类型?

不能以这种方式使用std::function

你可以自己滚动,但这需要一些工作。

这是一个草图:

template<class T, class A, class B>
struct sub{using type=T;};
template<class T, class A, class B>
using sub_t=typename sub<T,A,B>::type;
template<class T, class B>
struct sub<T,T,B>{using type=B;};
template<class R,class...Args,class A,class B>
struct sub<R(Args...),A,B>{
  using type=sub_t<R,A,B>(sub_t<Args,A,B>...);
};

写出上面的内容。它采用类型T,如果它与A匹配,则返回B。否则返回T。它也适用于函数签名。

我们可以将其与签名中的"flag"类型一起使用,以替换为函数对象本身的类型:

struct recurse{}; // flag type
// not needed in C++14:
template<class Sig>
using result_of_t=typename std::result_of<Sig>::type;
template<class Sig>
struct func {
  using Sig2=sub_t<Sig,recurse,func>;
  using function = std::function<Sig2>;
  function impl;
  template<class...Ts>
  result_of_t<function const&(Ts...)>
  operator()(Ts&&...ts)const
  {
    return impl(std::forward<Ts>(ts)...);
  }
};

那么func<recurse()>是一个函数对象,当被调用时,它返回一个func<recurse()>

事实证明,实现很简单,只需存储一个std::function<Sig2>并调用它

实例

请注意,如果您想避免通过引用捕获自己的副本以在lambda中返回*this,则y组合子可能很有用,因为通过引用捕获意味着有限的生存期(并避免使用共享ptr)。

其他有用的工作是增强sub以处理对-A的引用,甚至是包含A作为参数的模板。(通用子算法在C++中是不可行的,因为C++没有完全的元模板功能,但处理std中当前的每个模板类都很容易:它们都是纯类型模板,或std::array)。


为了完整起见,您可以将其添加到sub:中

// optional stuff for completeness:
template<class T,class A,class B>
struct sub<T&,A,B>{
  using type=sub_t<T,A,B>&;
};
template<class T,class A,class B>
struct sub<T*,A,B>{
  using type=sub_t<T,A,B>*;
};
template<template<class...>class Z,class... Ts,class A,class B>
struct sub<Z<Ts...>,A,B>{
  using type=Z<sub_t<Ts,A,B>...>;
};
template<template<class,size_t>class Z,class T,size_t n,class A,class B>
struct sub<Z<T,n>,A,B>{
  using type=Z<sub_t<T,A,B>,n>;
};
template<class T,size_t n,class A,class B>
struct sub<T[n],A,B>{
  using type=sub_t<T,A,B>[n];
};
template<class T,class A,class B>
struct sub<T[],A,B>{
  using type=sub_t<T,A,B>[];
};
template<class T,class A,class B>
struct sub<T const,A,B>{
  using type=sub_t<T,A,B> const;
};
template<class T,class A,class B>
struct sub<T volatile const,A,B>{
  using type=sub_t<T,A,B> volatile const;
};
template<class T,class A,class B>
struct sub<T volatile,A,B>{
  using type=sub_t<T,A,B> volatile;
};

现在,它可以递归地处理许多模板、数组、引用和指针,以及cv限定的类型。这允许你写一些类似的东西:

func< std::vector<recurse>() >

其是CCD_ 16返回CCD_。

请注意,这个过程并不是很完美,就好像some_template<recurse>不是一个有效的模板实例化一样,上面的操作就不起作用了。在这种情况下,需要一个陌生的版本,它采用可能应用的模板和参数,进行替换,然后是应用程序。