gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:21:17 25 4
gpt4 key购买 nike

我想创建模板类 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com