c++ - 如何在其他模板类中专门化模板类?

标签 c++ templates template-specialization

我想创建模板类 allocator_factory和模板化 arena_allocator在里面。至于arena_allocator继承自 std::allocator我必须为 arena_allocator<void> 创建特化, 但我不能。

编译器错误是:arena_alloc.h:25:37: error: too few template-parameter-lists

#pragma once

#include <memory>
#include <cstddef>


template <std::size_t Size, typename Tag>
class allocator_factory;


template <std::size_t Size, typename Tag>
class allocator_factory
{
public:
    static constexpr std::size_t size = Size;
    typedef Tag tag_type;

    template <typename T>
    class arena_allocator;
};



template <std::size_t Size, typename Tag>
class allocator_factory<Size, Tag>::arena_allocator<void> :
    public std::allocator<void>   //^ error here
{
    typedef std::allocator<void> Parent;
public:
    typedef typename Parent::value_type         value_type;
    typedef typename Parent::pointer            pointer;
    typedef typename Parent::const_pointer      const_pointer;
    typedef typename Parent::size_type          size_type;
    typedef typename Parent::difference_type    difference_type;

    typedef allocator_factory<Size,Tag> factory_type;

    template <typename U>
    struct rebind
    {
        typedef typename allocator_factory<size, tag_type>::template arena_allocator<U> other;
    };

    typedef typename Parent::propagate_on_container_move_assignment propagate_on_container_move_assignment;

    arena_allocator() throw() : Parent() {}
    arena_allocator(const arena_allocator& a) throw() : Parent(a) {}
    template <class U>
    arena_allocator(const arena_allocator<U>& a) throw() :Parent(a) {}
};

最佳答案

我不认为你可以在不完全特化封闭模板的情况下特化一个封闭的模板:

template<class T>
struct A {
    template<class U>
    struct B {};
};

template<>
template<>
struct A<int>::B<int> {}; // Okay.

template<>
template<class U>
struct A<int>::B<U*> {}; // Okay.

template<class T>
template<>
struct A<T>::B<int> {}; // error: enclosing class templates are not explicitly specialized

作为解决方法,将随附的模板提取到文件/命名空间范围内,并根据需要对其进行特殊化:

// Extracted template.
template <std::size_t Size, typename Tag, typename T>
class the_arena_allocator;

template <std::size_t Size, typename Tag>
class allocator_factory
{
public:
    static constexpr std::size_t size = Size;
    typedef Tag tag_type;

    template <typename T>
    using arena_allocator = the_arena_allocator<Size, Tag, T>;
};

// A partial specialization of the extracted template.
template <std::size_t Size, typename Tag>
class the_arena_allocator<Size, Tag, void> { /* ... */ };

关于c++ - 如何在其他模板类中专门化模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55399954/

相关文章:

c++ - OpenCV findContours 不工作

python - Python 可以调用使用 extern "C"和 ctypes 编译的 C++ DLL 库吗?

c++ - 错误[Lp001]内存不足,但我不应该这样做

c++ - 模板难题

c++ - 特化模板类的内部模板

c++ - 专门化采用通用引用参数的函数模板

c++ - 如果值未更改,是否允许更改对象的底层字节?

c++ - 如何在 gdb 中执行 `print`/evaluate c++ 模板函数

c - 用于 C 模板仿真的 Doxygen

c++ - 使用 C++ 模板覆盖遗留的 C 风格函数