递归取消隐藏基类成员

时间:2011-06-20 10:40:17

标签: c++ templates inheritance c++11 template-meta-programming

我尝试编写一个以函数元组为参数的类,并为函数的所有operator()重载argument_type。现在看起来像这样:

template<typename T>
struct holder {
  T t;
};

template<typename T, std::size_t i>
struct overload_helper : public holder<T>, public overload_helper<T, i - 1> {
  overload_helper(T t) : holder<T>({t}) {};
  typedef typename std::tuple_element<i - 1, T>::type inner_type;
  typename inner_type::result_type operator()(typename inner_type::argument_type x) { 
    return std::get<i - 1>(holder<T>::t)(x); }
};

template<typename T>
struct overload_helper<T, 1> {
  typedef typename std::tuple_element<0 ,T>::type inner_type;
  typename inner_type::result_type operator()(typename inner_type::argument_type x) { 
    return std::get<0>(holder<T>::t)(x); }
};

template<typename T>
struct overload : public overload_helper<T, std::tuple_size<T>::value>
{
  typedef void result_type;
  overload(const T& t) : overload_helper<T, std::tuple_size<T>::value>(t) { }
};


int main() {
  auto all = make_overload(std::make_tuple(
                 std::function<void(double)>([](double i) { 
                 std::cout << "double" << std::endl;
                   }), std::function<void(int)>([](int i) { 
                   std::cout << "int" << std::endl; })));

  all(1); //fails
  all(1.0);
}

问题是基类隐藏了operator()的每个递归定义。是否可以使用using递归取消隐藏所有定义,或者是获得模板化operator()的唯一方法,并使用boost::mpl选择正确的重载?

1 个答案:

答案 0 :(得分:6)

每个using overload_helper<T, i - 1>::operator()中的

overload_helper都可以完成这项工作,只要它们不含糊不清。