1

我正在尝试在 STL 容器(例如vectorlist. 这是我的实现:

#include <functional>
#include <algorithm>


template<class A, class B, template <class> class F>
F<B> fmap(F<A> &functor, std::function<B(A)> &f)
{
  F<B> newFunctor;

  return std::transform(begin(functor)
                , end(functor)
            , begin(newFunctor)     
            , f);
}

但是当我尝试用代码调用它时:

vector<int> v;

for(int i = 0; i < 5; i++) {
  v.push_back(i);
}

vector<int> w = fmap(v, [](int i) { return i + 1; });

我得到一个no matching function call错误。

我怎样才能让它工作?

4

3 回答 3

2

代码中有几处错误。正如已经指出的那样,第一件事是std::vector模板接受 2 个模板参数,即存储类型和分配器。即使第二个默认是std::allocator存储类型的实例化,它仍然是模板的参数。

您将遇到的第二个问题是,虽然您可以std::function从 lambda 创建 a,但 lambda 表达式不是 a std::function,因此编译器将无法匹配第二个参数。

于 2013-08-07T20:14:01.710 回答
0

矢量有 2 个模板参数

template < class T, class Alloc = allocator<T> > class vector; 
于 2013-08-07T19:34:26.000 回答
0

通过假设所有适用的容器类型都是模板类,其第一个参数是值类型,您可以从容器类型的确切声明结构中获得一些独立性。对于输出,生成一个具有不同值类型且所有其他模板参数相同的容器。这可以通过可以重新绑定具有不同值类型的容器的类型特征来实现:

template <typename Container>
struct container_rebind;

template <template <typename...> class Container, typename ValueType, typename... OtherArgs>
struct container_rebind<Container<ValueType, OtherArgs...>> {
    template <typename NewValueType>
    using rebind = Container<NewValueType, OtherArgs...>;
};

template <typename Container, typename NewValueType>
using ContainerRebind = typename container_rebind<Container>::template rebind<NewValueType>;

所以,例如,ContainerRebind<std::vector<int>, double>std::vector<double>。可以部分专门container_rebind化以支持其他类型的容器模板,例如那些具有非类型模板参数的容器模板。例如,添加对 的支持std::array留给读者。

于 2013-08-07T20:16:47.623 回答