c++ - 递归地取消隐藏基类成员

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

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

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< 选择正确重载的唯一方法

最佳答案

using overload_helper<T, i - 1>::operator()在每个 overload_helper应该完成这项工作,只要它们不含糊即可。

关于c++ - 递归地取消隐藏基类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6409953/

相关文章:

c++ - 我应该尝试在第 3 方库中修复一个可以说是糟糕的设计决策吗?

c++ - 将集合插入/读取到 map 中

c++ - 初始化模板类的静态成员

c++ - C++ 中的根基类

java - 为什么不允许重写方法中参数类型的差异(一个是原始方法,另一个是包装器)?

python - 如何避免使用 Python 继承重新定义默认参数

c++ - 如何在 win32 中更改工具栏按钮的位图?

c++ - 为什么构造函数上的显式说明符不能阻止向上转型?

c++ - 使用模板参数定义 Hana 结构

c++ - 两个模板类互相用作模板参数