Generic visitor base class template in C++ - overload issue

限于喜欢 提交于 2019-12-04 11:20:50
Xeo

The compiler doesn't know which base-class' visit function to call. See this question of mine. As such, as you correctly said, you need to make the functions available in the visitor class with using declarations. Sadly, you can't just use using visitor_base<T>::visit...;, as that is not a valid pattern. You have to recursively inherit from one base after another and everytime bring the base-class visits into the scope of the derived class:

template <typename T>
struct visitor_base {
    virtual void visit(T&) {};
};

template <typename Head, typename... Tail>
struct recursive_visitor_base
  : visitor_base<Head>
  , recursive_visitor_base<Tail...>
{
  using visitor_base<Head>::visit;
  using recursive_visitor_base<Tail...>::visit;
};

template<class T>
struct recursive_visitor_base<T>
  : visitor_base<T>
{
  using visitor_base<T>::visit;
};

template <typename... T>
struct visitor
  : recursive_visitor_base<T...>
{
  using recursive_visitor_base<T...>::visit;
};

Live example on Ideone (I had to tweak the partial spec a bit, since GCC 4.5.1 is a bit buggy in that part. Clang compiles the code shown in this answer just fine). Output:

that was a base.
that was 42
that was 2.79
that was 2.79
that was a base.
=================
that was a base.
that was 1804289383
that was 8.46931e+08
that was 1.68169e+09
that was a base.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!