Auto incremented integer as a template parameter

P

pastbin

Dear members,

I would like to know if it exists a technique that would make the
following code possible:

//----
template<int ID>
struct ident
{
//...
};

void create_ident()
{
// the function body would contain that kind of expression:

/*...*/new ident<AUTO_INCREMENT_COUNTER>();

// where AUTO_INCREMENT_COUNTER is controlled/generated
// by the compiler
}

int main()
{
create_ident(); // would create ident<0>()
create_ident(); // ident<1>()
//..
}
//----

I can't think of a solution for this problem. Of course I could make
function create_ident() templated and simply call create_ident<N>()
but this is not what i want.
What do you think of such a behavior ?

Thank you,

mark
 
S

Salt_Peter

Dear members,

I would like to know if it exists a technique that would make the
following code possible:

//----
template<int ID>
struct ident
{
//...

};

void create_ident()
{
// the function body would contain that kind of expression:

/*...*/new ident<AUTO_INCREMENT_COUNTER>();

// where AUTO_INCREMENT_COUNTER is controlled/generated
// by the compiler

}

int main()
{
create_ident(); // would create ident<0>()
create_ident(); // ident<1>()
//..}

//----

I can't think of a solution for this problem. Of course I could make
function create_ident() templated and simply call create_ident<N>()
but this is not what i want.
What do you think of such a behavior ?

Thank you,

mark

How were you planning to recover (or access) those allocations?
And does it make sense that each id is a new type, not just a new
object?

How about...

#include <iostream>
#include <ostream>
#include <vector>
#include <iterator>
#include <algorithm>

static unsigned counter;

class ident
{
unsigned m_id;
public:
ident() : m_id(counter++) { }
// friend op<<
friend std::eek:stream&
operator<<(std::eek:stream& os, const ident& i)
{
return os << i.m_id;
}
};

void push(std::vector< ident >& r_v)
{
ident id;
r_v.push_back(id);
}

int main()
{
const size_t Size(10);
ident array[Size];
std::vector< ident > identities(array, array + Size);

push(identities);
push(identities);

std::copy( identities.begin(),
identities.end(),
std::eek:stream_iterator< ident >( std::cout,
"\n") );
}

/*
0
1
2
3
4
5
6
7
8
9
10
11
*/

You might wrap your vector in its own class and just push() / create()
too.
Be aware that vector uses copy construction to populate elements,
which is why the above array was employed.
Allocation and deallocation is automatic, RAII is cool.
 

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

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top