0
template
<
    template <typename, typename>
        class storage_t,
    typename T,
    typename is_allocated
>
class Buffer : public storage_t<T, is_allocated> { ... };

template
<
    template <typename, typename>
        class storage_t,
    typename T = storage::UnknownType,
    typename is_allocated = std::false_type
>
class Example_Buffer
: public Buffer<storage_t, T, is_allocated> {
    constexpr Example_Buffer(
        typename storage_t<T, is_allocated>::iterator it) {}
};

Example_Buffer<...>继承自Buffer<...>Buffer<storage_t, T, is_allocated>继承自storage_t<T, is_allocated>storage_t<...>包括typedefs和静态 constexpr 数据。有没有办法通过继承访问这些typedefsstatic constexpr data构造函数?Example_Buffer(通过继承,也就是不使用storage_t<T, is_allocated>? 在同一个类中使用这种语法两次感觉有点奇怪。

随意问我是否需要详细说明。

4

1 回答 1

1

只要成员在 storage_t 中是公共的,它们就可以被继承和访问。您可以使用注入的类名和/或注入的基类名来访问这些依赖成员,

这里有几个选项..

#include <iostream>
#include <type_traits>
#include <typeinfo>

using namespace std;

template <typename A,typename B>
struct basic_storage
{
    using a_type = A;
    using b_type = B;
    static constexpr bool value = b_type::value;
};


template
<
    template <typename, typename>
        class storage_t,
    typename T,
    typename is_allocated
>
class Buffer : public storage_t<T, is_allocated> {

    public:
    using storage_type = storage_t<T, is_allocated>;
};

template
<
    template <typename, typename>
        class storage_t,
    typename T /*= storage::UnknownType*/,
    typename is_allocated = std::false_type
>
class Example_Buffer
: public Buffer<storage_t, T, is_allocated> {
    public:
    constexpr Example_Buffer(
        /*typename storage_t<T, is_allocated>::iterator it*/) {

            //using the members with the injected class name..
            using b_type = typename Example_Buffer::b_type;

            // or directly using injected class name..
            std::cout << typeid(typename Example_Buffer::a_type).name() << std::endl;
            std::cout << Example_Buffer::value << std::endl;

            // using storage_type defined in Buffer<...>
            using storage_type = typename Example_Buffer::storage_type;

            std::cout << typeid(typename storage_type::a_type).name() << std::endl;
            std::cout << storage_type::b_type::value << std::endl;
            std::cout << storage_type::value << std::endl;

        }
};


int main() {
    Example_Buffer<basic_storage,int,std::true_type>{};
    return 0;
}

演示

如果您想知道为什么不能只在派生类中访问 then 而不在它们前面加上Example_Buffer::基类名称,正如这篇文章所解释的那样,这是因为它们是依赖名称。

于 2018-11-01T18:56:53.067 回答