Initialising stl containers

  • Thread starter =?ISO-8859-1?Q?Mattias_Br=E4ndstr=F6m?=
  • Start date
?

=?ISO-8859-1?Q?Mattias_Br=E4ndstr=F6m?=

Hello!

Sometimes I get the urge to write something like the following template
(see the code below) to help me initialise stl containers. With this
template I could:

vector<int> v = Initializer<int, vector>()(1)(-1)(0);

instead of:

vector<int> v;
v.push_back(1);
v.push_back(-1);
v.push_back(0);

This brings a nice warm feeling to my tummy. Not only is it short and
clear but it seems I can also use this to initialise a static container
in one statement. I could also use it in an intialiser list of a
constructor if I wanted to:

class A
{
public:
A() : v_(Initializer<int, std::vector>()(1)(2)) { }
private:
std::vector<int> v_;
};

But something in the back of my head tells me that my initialiser
template is not 100% kosher.

Has anybody got some insight into this subject? Why haven't I seen a
template like this anywhere, in litterature or in real life projects? Is
there an achilles heel to my approach that I have missed?

Show me the light!

:.:: brasse

/**
* @brief
* This class helps with initialisation of containers.
*
* The following example shows how to decalare and initialise a
* <code>vector</code> of integers in one statement:
*
* @code
* vector<int> v = Initializer<int, vector>()(1)(-1)(0);
* @endcode
*
* This will give the same result as:
*
* @code
* vector<int> v;
* v.push_back(1);
* v.push_back(-1);
* v.push_back(0);
* @endcode
*
* Note: Using <code>Initializer</code> will actually cause the
* objects to be copied two times.
*/
template <typename T, template <typename T> class C>
class Initializer
{
public:
Initializer() { }

Initializer& operator()(const T& v)
{
c.push_back(v);
return *this;
}

operator C<T>()
{
return c;
}

private:
C<T> c;
};
 
J

Jonathan Turkanis

Mattias said:
Hello!

Sometimes I get the urge to write something like the following
template (see the code below) to help me initialise stl containers.
With this template I could:

vector<int> v = Initializer<int, vector>()(1)(-1)(0);
Has anybody got some insight into this subject? Why haven't I seen a
template like this anywhere, in litterature or in real life projects?
Is there an achilles heel to my approach that I have missed?

Try

http://www.boost.org/libs/assign/doc/index.html

Jonathan
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,239
Members
46,827
Latest member
DMUK_Beginner

Latest Threads

Top