c++ - 仿函数参数和结果的任意类型转换

标签 c++ c++11 functor template-meta-programming

我有这样一个类:

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;
};

最佳答案

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
};

关于c++ - 仿函数参数和结果的任意类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10326413/

相关文章:

c++ - 对在 Protocol Buffers 中使用 Message::ParseFromIstream 感到困惑

C++0x 可变参数模板通过引用传递

c++ - 为什么我无法进行此转换?

c++ - 如何根据 C++11 中的特定条件从 vector 中删除元素

c++ - std::move 触发析构函数?

haskell - 在 haskell 中如何确定一个类型是否为仿函数?

c++ - 为什么 clang 3.4 以如此奇怪的方式实现 `std::function`?

qt - 带有仿函数的 QAbstractItemModel foreach 迭代器 : is there a better way to do this?

C++ 将数组大小分配为变量并在运行时为变量赋值?

c++ - 在工厂或C++的类中包含数据库.h文件