3

我有一堂这样的课:

template <typename T>
struct operation {
    typedef T result_type;
    typedef ::std::shared_ptr<operation<T> > ptr_t;
};

我有一个匹配这种::std::function类型的函子:

::std::function<int(double, ::std::string)>

我想创建一个具有如下签名的函子:

operation<int>::ptr_t a_func(operation<double>::ptr_t, operation< ::std::string>::ptr_t);

我想以一种自动化的方式来做这件事,这样我就可以为任何给定的::std::function类型创建一个类似的函子。

最后,我想把这个皱纹放进去。这个:

::std::function<int(operation<double>::ptr_t, ::std::string)>

应该导致:

operation<int>::ptr_t a_func(operation<double>::ptr_t, operation< ::std::string>::ptr_t);

因为如果一个仿函数已经接受了一个operation<T>::ptr_t,这意味着它理解它们是什么并且愿意处理它们本身的异步性质。

我该怎么做?我在这里有一个天真的和部分工作的尝试:

template <typename argtype>
struct transform_type {
   typedef typename operation<argtype>::ptr_t type;
};

template <typename ResultType, typename... ArgTypes>
::std::function<typename transform_type<ResultType>::type(typename transform_type<ArgTypes...>::type)>
make_function(::std::function<ResultType(ArgTypes...)>)
{
   return nullptr;
}

它不会检测到已经是类型的参数std::shared_ptr<operation<T> >。并且 transform_type 的这种特化无法编译:

template <typename argtype>
struct transform_type<typename operation<argtype>::ptr_t>
{
   typedef typename stub_op<argtype>::ptr_t type;
};
4

2 回答 2

2
template<template<typename...> class F, typename Sig>
struct transform;

template<template<typename...> class F, typename R, typename... A>
struct transform<F, R(A...)> {
    using type = typename F<R>::ptr_t(typename F<A>::ptr_t...);
};

用法如下:

template<typename Sig>
void foo(std::function<Sig> f)
{
    using transformed_type = typename transform<operation, Sig>::type;
    std::function<transformed_type> g;
}

至于避免转换已经处于所需形式的类型的专业化:

template<typename T>
struct operation<std::shared_ptr<T>> {
    using ptr_t = std::shared_ptr<T>;
    using result_type = ptr_t; // Or perhaps this needs to be T, you haven't said
};
于 2012-04-26T06:56:19.440 回答
0

我相信我已经在R. Martinho Fernandez的帮助下解决了这个问题:

template <typename T>
struct is_op_ptr {
 private:
   // Returns false_type, which has a ::value that is false.
   template <class AT>
   static constexpr std::false_type is_it_a_ptr(...);

   // Returns true_type (if enable_if allows it to exist).
   template <class AT>
   static constexpr typename ::std::enable_if<
      ::std::is_same<
         AT,
         typename operation<typename AT::element_type::result_type>::ptr_t>::value,
      std::true_type>::type  // note the true_type return
   is_it_a_ptr(int); // no definition needed

 public:
   // do everything unevaluated
   static constexpr bool value = decltype(is_it_a_ptr<T>(0))::value;
};

template <typename T>
struct transform_type
   : ::std::conditional< is_op_ptr<T>::value, T, typename operation<T>::ptr_t>
{
};

这也允许我查询一个类型是否会在包装函数的构造中进行转换。

于 2012-04-26T03:32:11.740 回答