如何告诉类它将是另一种类型的父类,并且它可以从其子类访问某些数据成员?

时间:2017-11-26 21:56:29

标签: c++ c++17

我想定义一组模板函数,稍后我可以将它们添加到另一个类中,以便提供可以作用于某种类型的函数子集。

例如,这是一个调用size()的通用仿函数:

// provides the `size()` operation
template<class T>
struct size_op_t
{
    auto size() const noexcept
    {
        // we know that some class is inheriting from us here and that it will have
        // a data member called "value_"
        return value_.size(); // ERROR: there is no "value_" in size_op_t
    }
};

问题是value_中没有size_op_t个数据成员。因此,编译失败。但是,我知道size_op_t将由一个实际上包含value_数据成员的类继承。

这就是它的样子:

template<class T, template<class...> class... Ops> // functions compatible with T
struct viewer : public Ops<viewer<T>>... // available functions are inherited
{
    viewer(T const& value) noexcept : value_{ value } {}

    T const& value_;
};

然后可以像这样使用:

std::string str{ "abc" };
viewer<std::string, size_op_t/*other operations like begin_op_t, etc.*/> view{ str };
std::cout << view.size() << '\n'; // only provides the `size()` operation

我试图避免在每个xyz_op_t中存储引用,同时能够轻松地创建类似size_op_t等通用仿函数的自定义类似查看器的类型,我可以混合搭配取决于我想要的操作。

0 个答案:

没有答案