|
||||
|
Section 35:
|
[35.21] How can I create a container-template that allows my users to supply the type of the underlying container that actually stores the values?
First, let's clarify the question: the goal is to create a template Foo<>, but having the template parameter-list include some particular type of std::vector<T> or std::list<T> or some other (possibly non-standard) container to actually store the values. Here's one way to do that:
template<typename Underlying>
class Foo {
public:
// typename value_type is the type of the values within a Foo-container
typedef typename Underlying::value_type value_type;
void insert(const typename value_type& x)
{
← code to insert x into data_
}
...
private:
Underlying data_;
};
Foo<std::vector<int> > x;
Foo<std::list<double> > y;
If you want to allow your users to provide you with an underlying container
that does not necessarily have a value_type typedef (such as some
container from a third party), you could provide the value-type explicitly:
template<typename T, typename Underlying>
class Foo {
public:
// typename value_type is the type of the values within a Foo-container
typedef T value_type;
void insert(const typename value_type& x)
{
← code to insert x into data_
}
...
private:
Underlying data_;
};
Foo<int, std::vector<int> > x;
Foo<double, std::list<double> > y;
However you cannot (yet) provide an unspecified template as a template
parameter, such as this:
template<typename T, template<typename> class Underlying> ← conceptual only; not C++
class Foo {
public:
...
private:
Underlying<T> data_; ← conceptual only; not C++
};
Foo<int, std::vector> x; ← conceptual only; not C++
Foo<double, std::list> y; ← conceptual only; not C++
|
|||