通过继承模板模板参数来访问静态数据?

时间:2018-11-01 16:20:15

标签: c++11 templates inheritance static policy-based-design

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数据。是否可以通过继承在typedefs的构造函数中访问这些static constexpr dataExample_Buffer? (通过继承,即不使用storage_t<T, is_allocated>?在同一个类中两次使用此语法有点奇怪。

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

1 个答案:

答案 0 :(得分:1)

只要成员在storage_t中是公共的,它们就可以继承并可以访问。您可以使用injected class name和/或注入的基类名称来访问这些从属成员,

以下是一些选择。.

#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;
}

Demo

如果您想知道为什么不能访问该派生类,而没有在它们前面加上Example_Buffer::基类名称,正如this post所解释的那样,这是因为它们是从属名称。