泛型编程中的Concept, Model和Policy

时间:2022-06-12 22:47:46

A crude explanation

Concept

A set of requirements on a type, e.g. a RandomAccessible concept requires the type implements:operator[] (int) in O(1) time.

Model

When a type meet a concept, it's a model of that concept.

Policy

A unit of behaviour, which can combine with other units of behaviour to build complex classes. For illustration:

template<class T, class StoragePolicy>
class array : public StoragePolicy {
public:
T& operator[](int i) { return data[i]; };
}; // policy 1
template <class T, int N>
class fixed_storage {
T data[N];
}; // policy 2
template<class T>
class dynamic_storage{
T* data;
public:
void push_back(const T& val) {
// code for dynamic array insertationk
}
};

usage of policy:

int main(){
array<int, fixed_storage<int, 10>> fixed_array;
array<int, dynamic_storage<int>> dynamic_array;
}

Reference

More