我有这样一个类:
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/