如何将CRTP与可变参数模板一起使用?

时间:2013-04-06 19:21:47

标签: c++ templates c++11 variadic-templates crtp

假设我最初使用CRTP进行以下设计:

template<class Outputter> class Generator {
protected:
    vector<int> v;
private:
    void work(ostream& out) {
        // perform first part of some complex operations on v
        out << *static_cast<Outputter *>(this);
        // perform second part of some complex operations on v
        out << *static_cast<Outputter *>(this);
        // many more ....
        // perform some final actions
    }
public:
    Generator(unsigned length): v(length) {}
    friend ostream& operator<<(ostream& out, Outputter&& generator) {
        // perform some preparation work
        work(out);
        // perform some final actions
        return out;
    }
};

class SimpleDumpOutputter : public Generator<SimpleDumpOutputter> {
private:
    unsigned count;
public:
    SimpleDumpOutputter(unsigned length): Generator(length), count() {}
    friend ostream& operator<<(ostream& out, SimpleDumpOutputter& outputter) {
        out << "Step " << ++count << " of calculation: "
        copy(outputter.v.begin(), outputter.v.end(), ostream_iterator<int>(out, " "));
        out << endl;
        return out;
    }
};

class FancyOutputter : public Generator<FancyOutputter> { // create a graph using graphviz's dot language to visualise v
private:
    // abbreviated
public:
    FancyOutputter(unsigned length): Generator(length) {}
    friend ostream& operator<<(ostream& out, FancyOutputter& outputter) {
        // write statements to out
        return out;
    }
};

// some more different Outputters, for example an Outputter that creates a pretty LaTeX document

在此设计中,有一个Generator CRTP类模板,可以对vector<int> v执行复杂的计算,并使用派生类的友好operator<<在计算的每个步骤/部分打印结果

这是一个我想要实现的有趣概念:我希望在一次执行中以多种格式输出。具体来说,我以为我能做到:

template<class Outputters> class AggregateOutputter : public Generator<AggregateOutputter<Outputters...> > {
private:
    static const unsigned outputter_count = sizeof...(Outputters);
    typedef array<ostream *, outputter_count> DestArr;
    DestArr destinations;
public:
    AggregateOutputter(unsigned v_length, DestArr destinations): IsomerGenerator<AggregateOutputter<Outputters...> >(length), destinations(destinations) {}
    friend ostream& operator<<(ostream&, AggregateOutputter& outputter); // first argument is dummy, because we would use the ostreams in destinations
}

这个想法是,用户会使用AggregateOutputter<SimpleDumpOutputter, FancyOutputter并使用array两个ostream构建对象。每当Generator在输出类上调用operator<<时,AggregateOutputter将遍历ostream中的destinationsOutputters中的类型并调用类似于*dest_iter << *static_cast<Outputter_Iter>(this);

的内容

我不确定这会如何起作用。我不确定是否可以这种方式使用多重继承,是否可以在array和一组参数化类型之间“压缩”。在这种情况下有人知道吗?

2 个答案:

答案 0 :(得分:3)

我修改了你的原创设计。我认为当调用输出操作符时,Generator会做一堆计算,这至少可以说是令人惊讶的。此外,您的AggregateOutputter输出以忽略&lt;&lt;的详细信息也令人惊讶。此外,Outputter与Generator没有is-a关系。

我试图将问题分开,最后没有使用CRTP,而是使用可变参数模板,但我认为它可以满足您的需求。

http://ideone.com/xQrnW4

#include <vector>
#include <iostream>
#include <iterator>
#include <array>
using namespace std;

class Generator {
protected:
    vector<int> v;
public:
    Generator(unsigned length): v(length) {}

    template<class Outputter>
    void do_calculations_with_output(Outputter& out){
        // perform first part of some complex operations on v
        out.output(v);
        // perform second part of some complex operations on v
        out.output(v);
        // perform some final actions
    }

};

class SimpleDumpOutputter {
private:

    ostream* out;
    unsigned count;
public:
    SimpleDumpOutputter(ostream& os): out(&os), count() {}
    template<class C>
    void output(const C& c) {
        *out << "Step " << ++count << " of calculation: ";
        copy(c.begin(),c.end(), ostream_iterator<int>(*out, " "));
        *out << endl;
    }
};

class FancyOutputter {
    ostream* out;
    int count;
public:
    FancyOutputter(ostream& os): out(&os),count() {}
    template<class C>
    void output(const C& c) {
        // create a graph using graphviz's dot language to ease visualisation of v
        *out << "Step " << ++count << " of calculation: ";
       *out << "Graphviz output\n";
    }
};

template<class... Outputters> class AggregateOutputter : private Outputters... {
private:
   template<class First, class... Rest>
   struct output_helper{
      template<class C>
      static void do_output(AggregateOutputter* pthis,const C& c){
          static_cast<First*>(pthis)->output(c);
          output_helper<Rest...>::do_output(pthis,c);
      }

   };

   template<class First>
   struct output_helper<First>{
      template<class C>
      static void do_output(AggregateOutputter* pthis,const C& c){
          static_cast<First*>(pthis)->output(c);
      }

   };
public:
   template<class... Out>
    AggregateOutputter( Out&... out): Outputters(out)...{}
    template<class C>
    void output(const C& c) {
        output_helper<Outputters...>::do_output(this,c);
    }

};
int main(){

    AggregateOutputter<FancyOutputter,SimpleDumpOutputter> out(cout,cout);

    Generator g(10);

    g.do_calculations_with_output(out);

}

答案 1 :(得分:0)

好的,这是我在John Bandela的解决方案here的启发下提出的解决方案。 (请参阅我对答案的评论,为什么我认为他的方法不符合我的需要)

template<class... Outputters> class AggregateOutputter : public Generator<AggregateOutputter<Outputters...> > {
private:
    typedef array<ostream *, sizeof...(Outputters)> DestArr;
    DestArr destinations;
    typedef typename DestArr::iterator DestArrIter;
    struct OutputterHolder : public Outputters... {
        OutputterHolder(vector<int>& v): Outputters(v)... {}
    } outputter_holder;
    template<class First, class... Rest> struct OutputHelper {
        static void do_output(OutputterHolder *pthis, DestArrIter dest) {
            **dest << *static_cast<First *>(pthis);
            OutputHelper<Rest...>::do_output(pthis, ++dest);
        }
    };
    template<class First> struct OutputHelper<First> {
        static void do_output(OutputterHolder *pthis, DestArrIter dest) {
            **dest << *static_cast<First *>(pthis);
        }
    };
public:
    template<typename... OstreamStar> AggregateOutputter(unsigned length, OstreamStar... ostreams): Generator<AggregateOutputter<Outputters...> >(length), destinations{{ostreams...}}, outputter_holder(this->v) {
        static_assert(sizeof...(OstreamStar) == sizeof...(Outputters), "number of outputters and destinations do not match");
    }
    friend ostream& operator<<(ostream& dummy_out, AggregateOutputter& outputter) {
        OutputHelper<Outputters...>::do_output(&outputter.outputter_holder, outputter.destinations.begin());
        // possibly write some logging info to dummy_out
        return dummy_out;
    }
};

// to use this:
ofstream fout("gv.gv");
cout << AggregateOutputter<FancyOutputter, SimpleDumpOutputter>(length, &fout, &cout);

这个想法是除了John的答案中的output_helper(我已将其重命名为OutputHelper)之外,还有另一个名为struct的辅助OutputterHolder,它继承了来自所有Outputters。我还使用array ostream *来存储输出的目的地,并修改do_output也使用iterator以便正确的ostream可以匹配。

重要的是,为了配合更改,我已将vector<int> v中受保护的成员Generator更改为引用,即vector<int>& v,以便outputter_holder中的数据结构可以指代AggregateOutputter中的结构。这还需要在所有输出器中添加另一个构造函数,该构造函数需要vector<int>&。长度为v的原始构造函数现在将使用new分配内存。

我不确定我提出的这个解决方案是最好/最优雅的解决方案。