具有完全可维护性的多调度解决方案 [英] Multiple dispatch solution with full maintainability

查看:44
本文介绍了具有完全可维护性的多调度解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能想到一种通过以下 Object :: foo 重载之类实现多次调度的好方法吗?

Can someone think of a good way to implement multiple dispatch with something like the Object::foo overloads below?

class A {
    public:
        virtual void accept (Visitor&) = 0;
};

class B : public A {
    virtual void accept (Visitor&) override;
};

class C : public A {
    virtual void accept (Visitor&) override;
};

class D : public A {
    virtual void accept (Visitor&) override;
};

class Object {
    public:
        virtual double foo (A*, A*) { std::cout << "Object::foo A,A\n";  return 3.14; }
        virtual double foo (B*, B*) { std::cout << "Object::foo B,B\n";  return 3.14; }
        virtual double foo (B*, C*) { std::cout << "Object::foo B,C\n";  return 3.14; }
        virtual double foo (C*, B*) { std::cout << "Object::foo C,B\n";  return 3.14; }
        virtual double foo (C*, C*) { std::cout << "Object::foo C,C\n";  return 3.14; }
        virtual char foo (A*, A*, A*) const { std::cout << "Object::foo A,A,A\n";  return '&'; }
        virtual char foo (C*, B*, D*) const { std::cout << "Object::foo C,B,D\n";  return '!'; }  // Overload of foo with three arguments.
        virtual void bar (A*, A*, A*) const { std::cout << "Object::bar A,A,A\n"; }
        virtual void bar (B*, B*, B*) const { std::cout << "Object::bar B,B,B\n"; }
        virtual void bar (B*, C*, B*) const { std::cout << "Object::bar B,C,B\n"; }
        virtual void bar (B*, C*, C*) const { std::cout << "Object::bar B,C,C\n"; }
        virtual void bar (B*, C*, D*) const { std::cout << "Object::bar B,C,D\n"; }
        virtual void bar (C*, B*, D*) const { std::cout << "Object::bar C,B,D\n"; }
        virtual void bar (C*, C*, C*) const { std::cout << "Object::bar C,C,C\n"; }
        virtual void bar (D*, B*, C*) const { std::cout << "Object::bar D,B,C\n"; }
        double fooMultipleDispatch (A*, A*);
        char fooMultipleDispatch (A*, A*, A*);
        void barMultipleDispatch (A*, A*, A*);
        template <template <int...> class Z1, template <int...> class Z2, int... Is, int... Js>
        double multipleDispatch (const ObjectFooVisitor<2>& visitor, const Z1<Is...>&, const Z2<Js...>&) {return foo (visitor.getArray<Is>()[Js]...);}
        template <template <int...> class Z1, template <int...> class Z2, int... Is, int... Js>
        char multipleDispatch (const ObjectFooVisitor<3>& visitor, const Z1<Is...>&, const Z2<Js...>&) const {return foo (visitor.getArray<Is>()[Js]...);}
        template <template <int...> class Z1, template <int...> class Z2, int... Is, int... Js>
        void multipleDispatch (const ObjectBarVisitor& visitor, const Z1<Is...>&, const Z2<Js...>&) {bar (visitor.getArray<Is>()[Js]...);} 
};

我正在执行多个调度的客户端代码如下:

The client code I have working to carry out the multiple dispatch looks like this:

int main() {
    A* a[] = {new B, new C, new D};
    Object* object = new Object;

    double d = object->foo (a[0], a[1]);  // Object::foo A,A  (no multiple dispatch)
    d = object->fooMultipleDispatch (a[0], a[1]);  // Object::foo B,C
    std::cout << "d = " << d << std::endl;  // 3.12

    const char k = object->fooMultipleDispatch (a[1], a[0], a[2]);  // Object::foo C,B,D
    std::cout << "k = " << k << std::endl;  // !

    object->bar (a[1], a[0], a[2]);  // Object::bar A,A,A  (no multiple dispatch)
    object->barMultipleDispatch (a[1], a[0], a[2]);  // Object::bar C,B,D

    Thing* thing = new Thing;
    int num = thing->baz (a[1], a[0], a[2]);  // Thing::baz A,A,A  (no multiple dispatch)  
    num = thing->bazMultipleDispatch (a[1], a[0], a[2]);  // Thing::baz C,B,D
    std::cout << "num = " << num << std::endl;  // 5
}

您可以根据我的设计推断出,我的解决方案在维护类别中失败了.每次要分派具有重载的新函数,新的相应Visitor类,等等(例如,在这种情况下 ObjectFooVisitor ,函数 Object :: fooMultipleDispatch 等).理想的设计不应要求此类维护工作.

You can deduce by my design that my solution fails miserably in the maintenance category. Every time a new function with overloads is to be multiple dispatched, a new corresponding Visitor class, etc... (e.g. in this case ObjectFooVisitor, the function Object::fooMultipleDispatch, etc...) needs to be written. The ideal design should not require this type of maintenance work.

我仅对多个调度对象:: foo具有访问者功能的示例,如下所示:

An example Visitor function I have just to multiple dispatch Object::foo, looks like this:

template<>
class ObjectFooVisitor<2> : public Visitor {  // For Object::foo overrides with two arguments.
    private:
        std::tuple<std::array<B*, 2>, std::array<C*, 2>> tupleOfArrays;
        std::array<int, 2> tupleIndices;
// ....
};

double Object::fooMultipleDispatch (A* a1, A* a2) {
    ObjectFooVisitor<2> visitor;
    a1->accept(visitor);  // Stores the dynamic type of a1
    a2->accept(visitor);  // and a2 into ObjectFooVisitor<2>'s array data members.
    return MultipleDispatcher<Object, ObjectFooVisitor<2>, double, 2, 0, index_sequence<0>>(this, visitor).execute();  // 2 because there are two arguments in the Object::foo overloads.
}

因此,我遵循的主要思想是存储动态类型的指针数组的元组,然后使用此存储来调用适当的重载.但是必须有其他设计才能使它更好地工作.

So the main idea I'm following is to store a tuple of arrays of pointers of the dynamic types and then use this storage to call up the appropriate overload. But there must be other designs to get this working better.

如果您想看到它,这是我的完整解决方案(在GCC 4.9.2上编译,需要SFINAE支持).随时尝试对其进行改进,使其更易于维护,但是我确定需要新的设计.

In case you want to see it, here is my full solution (compiles on GCC 4.9.2, SFINAE support needed). Feel free to try to refine it so that it is more maintainable, but I'm sure a new design is needed.

#include <iostream>
#include <array>
#include <tuple>
#include <type_traits>

class Object;  class B;  class C;  class D;

class Visitor {
    public:
        virtual void visit (B*) = 0;
        virtual void visit (C*) = 0;
        virtual void visit (D*) = 0;
};

class A {
    public:
        virtual void accept (Visitor&) = 0;
};

class B : public A {
    virtual void accept (Visitor&) override;
};

class C : public A {
    virtual void accept (Visitor&) override;
};

class D : public A {
    virtual void accept (Visitor&) override;
};

template <int, int> struct ArrayType;  // Extra template parameter N needed here to allow std::array of any size.
template <int N> struct ArrayType<N,0> { using type = std::array<B*, N>; };
template <int N> struct ArrayType<N,1> { using type = std::array<C*, N>; };
template <int N> struct ArrayType<N,2> { using type = std::array<D*, N>; };

template <int> class ObjectFooVisitor;

template<>
class ObjectFooVisitor<2> : public Visitor {  // For Object::foo overrides with two arguments.
    private:
        std::tuple<std::array<B*, 2>, std::array<C*, 2>> tupleOfArrays;
        std::array<int, 2> tupleIndices;
        int numAccepted = 0;
    protected:
        virtual void visit (B* b) override {std::get<0>(tupleOfArrays)[numAccepted] = b;  tupleIndices[numAccepted++] = 0;}
        virtual void visit (C* c) override {std::get<1>(tupleOfArrays)[numAccepted] = c;  tupleIndices[numAccepted++] = 1;}
        virtual void visit (D*) override {}
    public:
        ObjectFooVisitor() { std::get<0>(tupleOfArrays) = {{nullptr, nullptr}};  std::get<1>(tupleOfArrays) = {{nullptr, nullptr}}; }
        template <int N> const typename ArrayType<2,N>::type& getArray() const {return std::get<N>(tupleOfArrays);}
        const std::array<int, 2>& getTupleIndices() const {return tupleIndices;}
};

template<>
class ObjectFooVisitor<3> : public Visitor {  // For Object::foo overrides with three arguments.
    private:
        std::tuple<std::array<B*, 3>, std::array<C*, 3>, std::array<D*, 3>> tupleOfArrays;
        std::array<int, 3> tupleIndices;
        int numAccepted = 0;
    protected:
        virtual void visit (B* b) override {std::get<0>(tupleOfArrays)[numAccepted] = b;  tupleIndices[numAccepted++] = 0;}
        virtual void visit (C* c) override {std::get<1>(tupleOfArrays)[numAccepted] = c;  tupleIndices[numAccepted++] = 1;}
        virtual void visit (D* d) override {std::get<2>(tupleOfArrays)[numAccepted] = d;  tupleIndices[numAccepted++] = 2;}
    public:
        ObjectFooVisitor() { std::get<0>(tupleOfArrays) = {{nullptr, nullptr, nullptr}};  std::get<1>(tupleOfArrays) = {{nullptr, nullptr, nullptr}};  std::get<2>(tupleOfArrays) = {{nullptr, nullptr, nullptr}}; }
        template <int N> const typename ArrayType<3,N>::type& getArray() const {return std::get<N>(tupleOfArrays);}
        const std::array<int, 3>& getTupleIndices() const {return tupleIndices;}
};

class ObjectBarVisitor : public Visitor {
    private:
        std::tuple<std::array<B*, 3>, std::array<C*, 3>, std::array<D*, 3>> tupleOfArrays;
        std::array<int, 3> tupleIndices;
        int numAccepted = 0;
    protected:
        virtual void visit (B* b) override {std::get<0>(tupleOfArrays)[numAccepted] = b;  tupleIndices[numAccepted++] = 0;}
        virtual void visit (C* c) override {std::get<1>(tupleOfArrays)[numAccepted] = c;  tupleIndices[numAccepted++] = 1;}
        virtual void visit (D* d) override {std::get<2>(tupleOfArrays)[numAccepted] = d;  tupleIndices[numAccepted++] = 2;}
    public:
        ObjectBarVisitor() { std::get<0>(tupleOfArrays) = {{nullptr, nullptr, nullptr}};  std::get<1>(tupleOfArrays) = {{nullptr, nullptr, nullptr}};  std::get<2>(tupleOfArrays) = {{nullptr, nullptr, nullptr}}; }
        template <int N> const typename ArrayType<3,N>::type& getArray() const {return std::get<N>(tupleOfArrays);}
        const std::array<int, 3>& getTupleIndices() const {return tupleIndices;}
};

class ThingBazVisitor : public Visitor {
    private:
        std::tuple<std::array<B*, 3>, std::array<C*, 3>, std::array<D*, 3>> tupleOfArrays;
        std::array<int, 3> tupleIndices;
        int numAccepted = 0;
    protected:
        virtual void visit (B* b) override {std::get<0>(tupleOfArrays)[numAccepted] = b;  tupleIndices[numAccepted++] = 0;}
        virtual void visit (C* c) override {std::get<1>(tupleOfArrays)[numAccepted] = c;  tupleIndices[numAccepted++] = 1;}
        virtual void visit (D* d) override {std::get<2>(tupleOfArrays)[numAccepted] = d;  tupleIndices[numAccepted++] = 2;}
    public:
        ThingBazVisitor() { std::get<0>(tupleOfArrays) = {{nullptr, nullptr, nullptr}};  std::get<1>(tupleOfArrays) = {{nullptr, nullptr, nullptr}};  std::get<2>(tupleOfArrays) = {{nullptr, nullptr, nullptr}}; }
        template <int N> const typename ArrayType<3,N>::type& getArray() const {return std::get<N>(tupleOfArrays);}
        const std::array<int, 3>& getTupleIndices() const {return tupleIndices;}
};

void B::accept (Visitor& visitor) {visitor.visit(this);}
void C::accept (Visitor& visitor) {visitor.visit(this);}
void D::accept (Visitor& visitor) {visitor.visit(this);}

class Object {
    public:
        virtual double foo (A*, A*) { std::cout << "Object::foo A,A\n";  return 3.14; }
        virtual double foo (B*, B*) { std::cout << "Object::foo B,B\n";  return 3.14; }
        virtual double foo (B*, C*) { std::cout << "Object::foo B,C\n";  return 3.14; }
        virtual double foo (C*, B*) { std::cout << "Object::foo C,B\n";  return 3.14; }
        virtual double foo (C*, C*) { std::cout << "Object::foo C,C\n";  return 3.14; }
        virtual char foo (A*, A*, A*) const { std::cout << "Object::foo A,A,A\n";  return '&'; }  // This is needed for the foo overload to be multiple dispatched, even if it is never used, otherwise the other possible foo overloads with three arguments will have no place to go to.
        virtual char foo (C*, B*, D*) const { std::cout << "Object::foo C,B,D\n";  return '!'; }  // Overload of foo with three arguments.  Furthermore, the function itself is const and returns char instead of double.  Simply define char fooMultipleDispatch (A*, A*, A*), ObjectFooVisitor<3> (the old ObjectFooVisitor now renamed to ObjectFooVisitor<2>) and overload multipleDispatch with char multipleDispatch (const ObjectFooVisitor<3>& visitor, const Z1<Is...>&, const Z2<Js...>&). 
        virtual void bar (A*, A*, A*) const { std::cout << "Object::bar A,A,A\n"; }
        virtual void bar (B*, B*, B*) const { std::cout << "Object::bar B,B,B\n"; }
        virtual void bar (B*, C*, B*) const { std::cout << "Object::bar B,C,B\n"; }
        virtual void bar (B*, C*, C*) const { std::cout << "Object::bar B,C,C\n"; }
        virtual void bar (B*, C*, D*) const { std::cout << "Object::bar B,C,D\n"; }
        virtual void bar (C*, B*, D*) const { std::cout << "Object::bar C,B,D\n"; }
        virtual void bar (C*, C*, C*) const { std::cout << "Object::bar C,C,C\n"; }
        virtual void bar (D*, B*, C*) const { std::cout << "Object::bar D,B,C\n"; }
        double fooMultipleDispatch (A*, A*);
        char fooMultipleDispatch (A*, A*, A*);
        void barMultipleDispatch (A*, A*, A*);
        template <template <int...> class Z1, template <int...> class Z2, int... Is, int... Js>
        double multipleDispatch (const ObjectFooVisitor<2>& visitor, const Z1<Is...>&, const Z2<Js...>&) {return foo (visitor.getArray<Is>()[Js]...);}
        template <template <int...> class Z1, template <int...> class Z2, int... Is, int... Js>
        char multipleDispatch (const ObjectFooVisitor<3>& visitor, const Z1<Is...>&, const Z2<Js...>&) const {return foo (visitor.getArray<Is>()[Js]...);}
        template <template <int...> class Z1, template <int...> class Z2, int... Is, int... Js>
        void multipleDispatch (const ObjectBarVisitor& visitor, const Z1<Is...>&, const Z2<Js...>&) {bar (visitor.getArray<Is>()[Js]...);} 
};

class Thing {
    public:
        virtual int baz (A*, A*, A*) { std::cout << "Thing::baz A,A,A\n";  return 5; }
        virtual int baz (B*, B*, B*) { std::cout << "Thing::baz B,B,B\n";  return 5; }
        virtual int baz (B*, C*, B*) { std::cout << "Thing::baz B,C,B\n";  return 5; }
        virtual int baz (B*, C*, C*) { std::cout << "Thing::baz B,C,C\n";  return 5; }
        virtual int baz (B*, C*, D*) { std::cout << "Thing::baz B,C,D\n";  return 5; }
        virtual int baz (C*, B*, D*) { std::cout << "Thing::baz C,B,D\n";  return 5; }
        virtual int baz (C*, C*, C*) { std::cout << "Thing::baz C,C,C\n";  return 5; }
        virtual int baz (D*, B*, C*) { std::cout << "Thing::baz D,B,C\n";  return 5; }
        int bazMultipleDispatch (A*, A*, A*);
        template <template <int...> class Z1, template <int...> class Z2, int... Is, int... Js>
        int multipleDispatch (const ThingBazVisitor& visitor, const Z1<Is...>&, const Z2<Js...>&) {return baz (visitor.getArray<Is>()[Js]...);}  // Since Thing only has baz interested in multiple dispatching, it does not need its own MultipleDispatch inner class like Object does (but if other Thing methods want multiple dispatching, then as in the Object::multipleDispatch overloads).
};

template <typename, typename, typename, int, int, typename, typename = void, int = 0> struct MultipleDispatcher;

template <typename T, typename V, typename R, int Num, int N, template <int...> class Z, int... Is, int I>
struct MultipleDispatcher<T, V, R, Num, N, Z<I, Is...>, typename std::enable_if<N != Num-1>::type> : MultipleDispatcher<T, V, R, Num, N, Z<I+1, Is...>, typename std::enable_if<N != Num-1>::type> {
    T* t;
    const V& visitor;
    MultipleDispatcher (T* o, const V& v) : MultipleDispatcher<T, V, R, Num, N, Z<I+1, Is...>, typename std::enable_if<N != Num-1>::type>(o,v), t(o), visitor(v) {}
    R execute();
};

template <typename T, typename V, typename R, int Num, int Last, template <int...> class Z, int... Is, int I>
struct MultipleDispatcher<T, V, R, Num, Last, Z<I, Is...>, typename std::enable_if<Last == Num-1>::type> : MultipleDispatcher<T, V, R, Num, Last, Z<I+1, Is...>, typename std::enable_if<Last == Num-1>::type> {
    T* t;
    const V& visitor;
    MultipleDispatcher (T* o, const V& v) : MultipleDispatcher<T, V, R, Num, Last, Z<I+1, Is...>, typename std::enable_if<Last == Num-1>::type>(o,v), t(o), visitor(v) {}
    R execute();
};

template <typename T, typename V, typename R, int Num, int N, template <int...> class Z, int... Is>
struct MultipleDispatcher<T, V, R, Num, N, Z<Num, Is...>, typename std::enable_if<N != Num-1>::type> {
    T* t;
    const V& visitor;
    MultipleDispatcher (T* o, const V& v) : t(o), visitor(v) {}
    R execute() {return R();}  // End of recursion
};

template <typename T, typename V, typename R, int Num, int Last, template <int...> class Z, int... Is>
struct MultipleDispatcher<T, V, R, Num, Last, Z<Num, Is...>, typename std::enable_if<Last == Num-1>::type> {  // This unique specialization is needed to avoid compiling ambiguity.
    T* t;
    const V& visitor;
    MultipleDispatcher (T* o, const V& v) : t(o), visitor(v) {}
    R execute() {return R();}  // End of recursion
};

template <typename T, typename V, typename R, int Num, int N, template <int...> class Z, int... Is, int I>
R MultipleDispatcher<T, V, R, Num, N, Z<I, Is...>, typename std::enable_if<N != Num-1>::type>::execute() {
    if (I == visitor.getTupleIndices()[N])
        return MultipleDispatcher<T, V, R, Num, N+1, Z<0, I, Is...>, void>(t, visitor).execute();  // Do we need to specify the std::enable_if part here?  Apparently not.  We will allow N+1 to be anything, and there is apparently no ambiguity.
    else
        return MultipleDispatcher<T, V, R, Num, N, Z<I+1, Is...>, typename std::enable_if<N != Num-1>::type>::execute();
}

template <int...> struct index_sequence {};

template <int N, int... Is>
struct make_index_sequence_helper : make_index_sequence_helper<N-1, N-1, Is...> {};

template <int... Is>
struct make_index_sequence_helper<0, Is...> {
    using type = index_sequence<Is...>;
};

template <int N>
using make_index_sequence = typename make_index_sequence_helper<N>::type;

template <typename, typename> struct ReverseHelper;

template <template <int...> class Z, typename Pack>
struct ReverseHelper<Z<>, Pack> {
    using type = Pack;
};

template <template <int...> class Z, int First, int... Rest, int... Is>
struct ReverseHelper<Z<First, Rest...>, Z<Is...>> : ReverseHelper<Z<Rest...>, Z<First, Is...>> {};

template <typename> struct Reverse;

template <template <int...> class Z, int... Is>
struct Reverse<Z<Is...>> : ReverseHelper<Z<Is...>, Z<>> {};

template <typename T, typename V, typename R, int Num, int Last, template <int...> class Z, int... Is, int I>
R MultipleDispatcher<T, V, R, Num, Last, Z<I, Is...>, typename std::enable_if<Last == Num-1>::type>::execute() {
    if (I == visitor.getTupleIndices()[Last])
        return t->template multipleDispatch (visitor, typename Reverse<Z<I, Is...>>::type{}, make_index_sequence<Num>{});  // This compiles on GCC 4.9.2 but not on GCC 4.8.1. Template disambiguator needed.
    else
        return MultipleDispatcher<T, V, R, Num, Last, Z<I+1, Is...>, typename std::enable_if<Last == Num-1>::type>::execute();
}

double Object::fooMultipleDispatch (A* a1, A* a2) {
    ObjectFooVisitor<2> visitor;
    a1->accept(visitor);  // Stores the dynamic type of a1
    a2->accept(visitor);  // and a2 into ObjectFooVisitor<2>'s array data members.
    return MultipleDispatcher<Object, ObjectFooVisitor<2>, double, 2, 0, index_sequence<0>>(this, visitor).execute();  // 2 because there are two arguments in the Object::foo overloads.
}

char Object::fooMultipleDispatch (A* a1, A* a2, A* a3) {
    ObjectFooVisitor<3> visitor;
    a1->accept(visitor);
    a2->accept(visitor);
    a3->accept(visitor);
    return MultipleDispatcher<Object, ObjectFooVisitor<3>, char, 3, 0, index_sequence<0>>(this, visitor).execute();  // 3 because there are three arguments in this particular Object::foo overload.
}

void Object::barMultipleDispatch (A* a1, A* a2, A* a3) {
    ObjectBarVisitor visitor;
    a1->accept(visitor);
    a2->accept(visitor);
    a3->accept(visitor);
    MultipleDispatcher<Object, ObjectBarVisitor, void, 3, 0, index_sequence<0>>(this, visitor).execute();  // 3 because there are two arguments in the Object::foo overloads.
}

int Thing::bazMultipleDispatch (A* a1, A* a2, A* a3) {
    ThingBazVisitor visitor;
    a1->accept(visitor);
    a2->accept(visitor);
    a3->accept(visitor);
    return MultipleDispatcher<Thing, ThingBazVisitor, int, 3, 0, index_sequence<0>>(this, visitor).execute();  // 3 because there are three arguments in the Thing::baz overloads.
}

// Test

int main() {
    A* a[] = {new B, new C, new D};
    Object* object = new Object;

    double d = object->foo (a[0], a[1]);  // Object::foo A,A  (no multiple dispatch)
    d = object->fooMultipleDispatch (a[0], a[1]);  // Object::foo B,C
    std::cout << "d = " << d << std::endl;  // 3.12

    const char k = object->fooMultipleDispatch (a[1], a[0], a[2]);  // Object::foo C,B,D
    std::cout << "k = " << k << std::endl;  // !

    object->bar (a[1], a[0], a[2]);  // Object::bar A,A,A  (no multiple dispatch)
    object->barMultipleDispatch (a[1], a[0], a[2]);  // Object::bar C,B,D

    Thing* thing = new Thing;
    int num = thing->baz (a[1], a[0], a[2]);  // Thing::baz A,A,A  (no multiple dispatch)  
    num = thing->bazMultipleDispatch (a[1], a[0], a[2]);  // Thing::baz C,B,D
    std::cout << "num = " << num << std::endl;  // 5
}

推荐答案

我为多次调度所做的工作(将我的评论转化为答案):

What I have done for multiple dispatch (turn out my comment into answer):

// Generic IVisitor
// Do: using MyIVisitor = IVisitorTs<Child1, Child2, ...>
template <typename ... Ts> class IVisitorTs;

template <typename T, typename ... Ts>
class IVisitorTs<T, Ts...> : public IVisitorTs<Ts...>
{
public:
    using tuple_type = std::tuple<T, Ts...>;
    using IVisitorTs<Ts...>::visit;

    virtual ~IVisitorTs() = default;
    virtual void visit(const T& t) = 0;
};

template <typename T> class IVisitorTs<T>
{
public:
    using tuple_type = std::tuple<T>;

    virtual ~IVisitorTs() = default;
    virtual void visit(const T& t) = 0;
};

namespace detail {

// retrieve the index of T in Ts...
template <typename T, typename ... Ts> struct get_index;

template <typename T, typename ... Ts>
struct get_index<T, T, Ts...> : std::integral_constant<std::size_t, 0> {};

template <typename T, typename Tail,  typename ... Ts>
struct get_index<T, Tail, Ts...> :
        std::integral_constant < std::size_t, 1 + get_index<T, Ts...>::value > {};

// retrieve the index of T in Tuple<Ts...>
template <typename T, typename Tuple> struct get_index_in_tuple;

template <typename T, template <typename...> class C, typename ... Ts>
struct get_index_in_tuple<T, C<Ts...>> : get_index<T, Ts...> {};

// get element of a multiarray
template <std::size_t I>
struct multi_array_getter
{
    template <typename T, std::size_t N>
    static constexpr auto get(const T& a, const std::array<std::size_t, N>& index)
    -> decltype(multi_array_getter<I - 1>::get(a[index[N - I]], index))
    {
        return multi_array_getter<I - 1>::get(a[index[N - I]], index);
    }
};

template <>
struct multi_array_getter<0>
{
    template <typename T, std::size_t N>
    static constexpr auto get(const T& a, const std::array<std::size_t, N>& index)
    -> decltype(a)
    {
        return a;
    }
};

// Provide an implementation of visitor
// by forwarding to C implementation (which may be non virtual)
template <typename IVisitor, typename C, typename...Ts> struct IVisitorImpl;

template <typename IVisitor, typename C, typename T, typename...Ts>
struct IVisitorImpl<IVisitor, C, T, Ts...> : IVisitorImpl<IVisitor, C, Ts...>
{
    virtual void visit(const T& t) override { C::visit(t); }
};

template <typename IVisitor, typename C, typename T>
struct IVisitorImpl<IVisitor, C, T> : IVisitor, C
{
    virtual void visit(const T& t) override { C::visit(t); }
};

// helper to expand child type to IVisitorImpl
template <typename IVisitor, typename C>
struct IVisitorImplType;

template <typename ... Ts, typename C>
struct IVisitorImplType<IVisitorTs<Ts...>, C>
{
    using type = IVisitorImpl<IVisitorTs<Ts...>, C, Ts...>;
};

// Create an multi array of pointer of function
// (with all combinaisons of overload).
template <typename Ret, typename F, typename Arg>
class GetAllOverload
{
private:
    template <typename...Ts>
    struct Functor
    {
        // function which will be in array.
        static Ret call(F&f, const Arg& arg)
        {
            return call_helper(f, arg, make_index_sequence<sizeof...(Ts)>());
        }
    private:
        // The final dispatched function
        template <std::size_t ... Is>
        static Ret call_helper(F&f, const Arg& arg, index_sequence<Is...>)
        {
            using RetTuple = std::tuple<Ts&...>;
            // static cast is suffisant if arg is the abstract type
            // when given arg is concrete type, reinterpret_cast is required.
            // TODO: build a smaller table with only possible value to avoid that
            return f(reinterpret_cast<typename std::tuple_element<Is, RetTuple>::type>(std::get<Is>(arg))...);
        }
    };

    // helper class to create the multi array of function pointer
    template <std::size_t N, typename Tuple, typename...Ts>
    struct Builder;

    template <typename...Ts, typename...Ts2>
    struct Builder<1, std::tuple<Ts...>, Ts2...>
    {
        using RetType = std::array<Ret (*)(F&, const Arg&), sizeof...(Ts)>;

        static constexpr RetType build()
        {
            return RetType{ &Functor<Ts2..., Ts>::call... };
        }
    };

    template <std::size_t N, typename ...Ts, typename...Ts2>
    struct Builder<N, std::tuple<Ts...>, Ts2...>
    {
        template <typename T>
        using RecType = Builder<N - 1, std::tuple<Ts...>, Ts2..., T>;
        using T0 = typename std::tuple_element<0, std::tuple<Ts...>>::type;
        using RetType = std::array<decltype(RecType<T0>::build()), sizeof...(Ts)>;

        static constexpr RetType build() {
            return RetType{ RecType<Ts>::build()... };
        }
    };

public:
    template <std::size_t N, typename VisitorTuple>
    static constexpr auto get()
    -> decltype(Builder<N, VisitorTuple>::build())
    {
        return Builder<N, VisitorTuple>::build();
    }
};

template <typename Ret, typename IVisitor, typename F, std::size_t N>
class dispatcher
{
private:
    std::array<std::size_t, N> index;

    struct visitorCallImpl
    {
        template <typename T>
        void visit(const T&) const
        {
            *index = get_index_in_tuple<T, IVisitor>::value;
        }

        void setIndexPtr(std::size_t& index) { this->index = &index; }
    private:
        std::size_t* index = nullptr;
    };

    template <std::size_t I, typename Tuple>
    void set_index(const Tuple&t)
    {
        using VisitorType = typename IVisitorImplType<IVisitor, visitorCallImpl>::type;
        VisitorType visitor;
        visitor.setIndexPtr(index[I]);

        std::get<I>(t).accept(visitor);
    }
public:
    template <typename Tuple, std::size_t ... Is>
    Ret operator () (F&& f, const Tuple&t, index_sequence<Is...>)
    {
        const int dummy[] = {(set_index<Is>(t), 0)...};
        static_cast<void>(dummy); // silent the warning unused varaible
        constexpr auto a = GetAllOverload<Ret, F&&, Tuple>::
            template get<sizeof...(Is), typename IVisitor::tuple_type>();
        auto func = multi_array_getter<N>::get(a, index);
        return (*func)(f, t);
    }
};

} // namespace detail

template <typename Ret, typename Visitor, typename F, typename ... Ts>
Ret dispatch(F&& f, Ts&...args)
{
    constexpr std::size_t size = sizeof...(Ts);
    detail::dispatcher<Ret, Visitor, F&&, size> d;
    return d(std::forward<F>(f), std::tie(args...), make_index_sequence<size>());
}

示例用法

struct A;
struct B;
struct C;
struct D;

using IAVisitor = IVisitorTs<A, B, C, D>;

struct A {
    virtual ~A() = default;
    virtual void accept(IAVisitor& v) const { v.visit(*this); }
};
struct B : A {
    virtual void accept(IAVisitor& v) const override { v.visit(*this); }
};

struct C : A {
    virtual void accept(IAVisitor& v) const override { v.visit(*this); }
};
struct D : A {
    virtual void accept(IAVisitor& v) const override { v.visit(*this); }
};

class Object {
    public:
        virtual double foo (A*, A*) { std::cout << "Object::foo A,A\n";  return 3.14; }
        virtual double foo (B*, B*) { std::cout << "Object::foo B,B\n";  return 3.14; }
        virtual double foo (B*, C*) { std::cout << "Object::foo B,C\n";  return 3.14; }
        virtual double foo (C*, B*) { std::cout << "Object::foo C,B\n";  return 3.14; }
        virtual double foo (C*, C*) { std::cout << "Object::foo C,C\n";  return 3.14; }
        virtual char foo (A*, A*, A*) const { std::cout << "Object::foo A,A,A\n";  return '&'; }
        virtual char foo (C*, B*, D*) const { std::cout << "Object::foo C,B,D\n";  return '!'; }  // Overload of foo with three arguments.
        virtual void bar (A*, A*, A*) const { std::cout << "Object::bar A,A,A\n"; }
        virtual void bar (B*, B*, B*) const { std::cout << "Object::bar B,B,B\n"; }
        virtual void bar (B*, C*, B*) const { std::cout << "Object::bar B,C,B\n"; }
        virtual void bar (B*, C*, C*) const { std::cout << "Object::bar B,C,C\n"; }
        virtual void bar (B*, C*, D*) const { std::cout << "Object::bar B,C,D\n"; }
        virtual void bar (C*, B*, D*) const { std::cout << "Object::bar C,B,D\n"; }
        virtual void bar (C*, C*, C*) const { std::cout << "Object::bar C,C,C\n"; }
        virtual void bar (D*, B*, C*) const { std::cout << "Object::bar D,B,C\n"; }
        double fooMultipleDispatch (A*, A*);
        char fooMultipleDispatch (A*, A*, A*);
};

class FooDispatcher
{
public:
    explicit FooDispatcher(Object& object) : object(object) {}

    template <typename T1, typename T2>
    double operator() (T1& a1, T2& a2) const
    {
        return object.foo(&a1, &a2);
    }

    template <typename T1, typename T2, typename T3>
    char operator() (T1& a1, T2& a2, T3& a3) const
    {
        return object.foo(&a1, &a2, &a3);
    }
private:
    Object& object;
};

double Object::fooMultipleDispatch (A* a1, A* a2)
{
    return dispatch<double, IAVisitor>(FooDispatcher(*this), *a1, *a2);
}
char Object::fooMultipleDispatch (A* a1, A* a2, A* a3)
{
    return dispatch<char, IAVisitor>(FooDispatcher(*this), *a1, *a2, *a3);
}


int main() {
    A a_a;
    B a_b;
    C a_c;
    D a_d;
    A* a[] = {&a_b, &a_c, &a_d, &a_a};
    Object object;

    double d = object.foo (a[0], a[1]);  // Object::foo A,A  (no multiple dispatch)
    d = object.fooMultipleDispatch (a[0], a[1]);  // Object::foo B,C
    std::cout << "d = " << d << std::endl;  // 3.14

    object.fooMultipleDispatch (a[0], a[3]);  // B,A -> so best match is Object::foo A,A

    const char k = object.fooMultipleDispatch (a[1], a[0], a[2]);  // Object::foo C,B,D
    std::cout << "k = " << k << std::endl;  // !
}

在线示例

这篇关于具有完全可维护性的多调度解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆