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.MartinhoFernandezの助けを借りてそれを理解したと信じています:

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 に答える