功能性C++通过模板滥用

Wug*_*Wug 5 c++ collections templates functional-programming template-templates

我决定尝试使用模板在C++中编写功能映射实现,这就是我提出的:

template <
    class U, 
    class V, 
    template <class> class T 
>

class T<V> WugMap(
    class T<U>::const_iterator first, 
    class T<U>::const_iterator second, 
    V (U::*method)() const)

{
    class T<V> collection;
    while (first != second)
    {
        collection.insert(collection.end(), ((*(first++)).*method)());
    }
    return collection;
}
Run Code Online (Sandbox Code Playgroud)

现在这一切都很好,花花公子,甚至编译.问题是,我不知道如何实际调用它.

尝试天真的方式会产生以下错误:

prog.cpp:42: error: no matching function for call to 
‘WugMap(__gnu_cxx::__normal_iterator<Container*, std::vector<Container, 
std::allocator<Container> > >, __gnu_cxx::__normal_iterator<Container*, 
std::vector<Container, std::allocator<Container> > >, int (Container::*)()const)’
Run Code Online (Sandbox Code Playgroud)

据我所知,所有论据都是正确的.gcc根本没有提出任何替代方案,这让我相信我对WugMap的定义是可疑的,但它编译得很好,所以我很丢失.任何人都可以引导我度过这种愚蠢吗?

如果有人可以建议一个更好的方法来编写这样的函数来支持使用包含任何类型对象的任何类型的集合,我将考虑更改它.

到目前为止,这是我的想法.

我目前正在使用Ideone,它使用的是C++ 03,gcc 4.3.4.

附录1

这在C++ 11中是否可行?有人暗示它是.我知道C++ 11中的模板支持不同数量的参数,因此我也会修改我的要求以适应这种情况.我会付出一些努力来写一些东西,但与此同时,这里是我正在寻找的要求:

  • 应该有如下签名:

    C2<V, ...> map(const C1<U, ...>&, V (U::*)(...), ...)
    
    Run Code Online (Sandbox Code Playgroud)

    这是采用一些集合C1,包含U类型的元素,通过引用构造了一些默认参数,并且还采用了一些成员函数(返回V并获取了一些未知类型的参数),然后取order,要传递给成员函数的参数.该函数最终将返回包含类型为V的元素的类型C2的集合,并使用未知数量的默认参数进行初始化.

  • 应该是可链接的:

    vector<int> herp = map(
                       map(
                            set<Class1, myComparator>(),
                       &Class1::getClass2, 2, 3),
                       &Class2::getFoo);
    
    Run Code Online (Sandbox Code Playgroud)
  • 如果我在使用时不需要模板参数或任何其他额外的冗长,则可以获得奖励积分.

std::transform 是伟大的,但不可链接.

Die*_*ühl 4

模板参数永远不能从嵌套类型中推导出来。即使可以从成员函数指针推导出UV,也无法推导出模板类型T

在ideone的链接中显式指定模板参数(在编写上面的语句之前我没有链接)也不起作用,主要是因为 的模板参数std::vector不仅仅是单一类型Tstd::vector采用值类型和分配器类型。修复问题变得相当难看:

#include <vector>
#include <iostream>

using namespace std;

class Container
{
public:
    Container() {}
    Container(int _i) : i(_i) {}

    int get_i() const {return i;}

    int i;
};

    template <
        class U, 
        class V, 
        template <typename...> class T 
    >

    T<V> WugMap(
        typename T<U>::const_iterator first, 
        typename T<U>::const_iterator second, 
        V (U::*method)() const)
    {
        T<V> collection;
        while (first != second)
        {
            collection.insert(collection.end(), ((*(first++)).*method)());
        }
        return collection;
    }

int main()
{
    vector<Container> containers;
    for (int i = 0; i < 10; ++i) containers.push_back((Container(i)));

    WugMap<Container, int, std::vector>(
        containers.begin(), containers.end(), &Container::get_i);
}
Run Code Online (Sandbox Code Playgroud)