Visitor and templated virtual methods

时间秒杀一切 提交于 2019-12-04 02:20:15

oh, I see what you're after. Try something like this:



template < typename Impl >
struct Funky_Visitor_Base : Visitor_Base
{
  // err...
  virtual void operator()(Base_Int& b) { Impl::apply(b) }
  virtual void operator()(Base_Long& b) { Impl::apply(b) }
  virtual void operator()(Base_Short& b) { Impl::apply(b) }
  virtual void operator()(Base_UInt& b) { Impl::apply(b) }
  virtual void operator()(Base_ULong& b) { Impl::apply(b) }

  // this actually needs to be like so:
  virtual void operator()(Base_UShort& b)
  {
    static_cast<impl *const>(this)->apply(b) 
  }
};

struct weird_visitor : Funky_Visitor_Base<weird_visitor>
{
  // Omit this if you want the compiler to throw a fit instead of runtime error.
  template < typename T >
  void apply(T & t)
  {
    std::cout << "not implemented.";
  }

  void apply(Base_UInt & b) { std::cout << "Look what I can do!"; }
};

That said, you should look into the acyclic visitor pattern. It has misunderstood visitors built into the framework so you don't have to implement functions for stuff you'll never call.

Funny thing is that I actually used something very similar to this to build an acyclic visitor for a list of types. I applied a metafunction that basically builds Funky_Visitor_Base and turns an operator (something with an apply() like I show) into a visitor for that complete list. The objects are reflective so the apply() itself is actually a metafunction that builds based on whatever type it's hitting. Pretty cool and weird actually.

In your derived visitor class, Visitor_Cout, the operator() template does not override the operator() in the Visitor_Base. Per the C++03 standard (14.5.2/4):

A specialization of a member function template does not override a virtual function from a base class. [Example:

class B {
    virtual void f(int);
};

class D : public B {
    template <class T> void f(T);  // does not override B::f(int)
    void f(int i) { f<>(i); }      // overriding function that calls
                                   // the template instantiation
};

—end example]

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