我正在研究基于政策的设计,并创造了一个人为的例子。
#include <iostream>
#include <string>
template <typename T>
struct NewAllocator
{
T* Allocate(){
std::cout << "Allocated with new\n";
return nullptr;
}
};
template <typename T>
struct MallocAllocator
{
T* Allocate(){
std::cout << "Allocated with malloc\n";
return nullptr;
}
};
template <typename T>
struct CustomAllocator
{
CustomAllocator(const char* name)
:alloctr_name{name}
{}
T* Allocate(){
std::cout << "Allocated with custom\n";
return nullptr;
}
// Enriched behaviour
void print_name()
{
std::cout << "Name of the allocator is: " << alloctr_name;
}
std::string alloctr_name;
};
template <typename T, template <typename Allocated> typename AllocationPolicy = NewAllocator>
struct my_container : public AllocationPolicy<T>
{
my_container()
:begin{AllocationPolicy<T>::Allocate()}
{}
// Host can use enriched behaviour from policies
my_container(const char* alloctr_name)
:AllocationPolicy<T>(alloctr_name)
,begin{AllocationPolicy<T>::Allocate()}
{}
// template only initialized if used
void print_allocator_name()
{
AllocationPolicy<T>::print_name();
}
T *begin;
};
这是按预期工作但我很好奇。在my_container
的第一个构造函数中,我调用策略类的Allocate
方法将成员初始化为begin{AllocationPolicy<T>::Allocate()}
,正如我所说的那样。但是,如果我尝试在同一行执行begin{Allocate()}
,则会收到错误消息,指出Allocate
是未声明的标识符。为什么会这样?这不是虚函数或任何东西。 Allocate
是我基类的成员函数,我不应该在没有任何资格的情况下访问它吗?