need a virtual template member workaround

假如想象 提交于 2019-11-28 06:54:05

What you should do is separate the BaseVisitor.

class BaseVisited;
class BaseVisitorInternal {
public:
    virtual void visit(BaseVisited*) = 0;
    virtual ~BaseVisitorInternal() {}
};
class BaseVisited {
    BaseVisited();
    virtual void accept(BaseVisitorInternal* visitor) { visitor->visit(this); }
};
template<typename T> class BaseVisitor : public BaseVisitorInternal {
    void visit(BaseVisited* visited);
};

If you need BaseVisited's derived classes to be templated too AND pass their correct types/overloads to visit, you're officially dead.

I came up with something slightly different than DeadMG:

class BaseVisited;

class IVisitor {
  public:
    virtual void visit(BaseVisited *visited) = 0;
    virtual ~IVisitor();
};

template <typename T>
class BaseVisitor : public IVisitor {
  public:
    BaseVisitor();
    virtual void visit(BaseVisited *visited);
    virtual ~BaseVisitor();
    virtual T result();
};


class BaseVisited {
  public:
    BaseVisited();
    virtual void accept(IVisitor *visitor) { visitor->visit(this); };
    virtual ~BaseVisited();
};

Mine has an extra result() member function that lets you retrieve the result of the last visit.

You cannot declare/define templated virtual functions. The reason is that the virtual dispatch mechanism must be known when the compiler sees the base class definition, but templates are compiled on demand.

With the common vtable implementation the issue is that the number of entries that the compiler would have to reserve for the virtual function is undefined (how many different instantiations of the type can there be?), as is the order of them. If you declare the class:

class base {
public:
   virtual void foo();
   virtual int bar();
};

The compiler can reserve two entries in the vtable for the pointers to foo and bar in the vtable, and the vtable is perfectly defined by just inspecting the class definition. This cannot be achieved with templated functions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!