Velocity Reviews

Velocity Reviews (
-   C++ (
-   -   calculate number of template instantiations (

Ruslan Mullakhmetov 10-25-2011 01:05 PM

calculate number of template instantiations
Hi folks,

I got an interesting problem to play with templates. It's not
abstract and come from real life. I'm not sure wether it has solution
within C++, so I need advise and you opinions.

In brief: I need to calculate number of template instantiation,
reasoning below.

What I need. Assume I have some template Templ<T>. In the code I
instantiated it several times like Templ<A>, Templ<B>, ... Next I need
to get number of instantiation _prior_ to creating any of instances of
instantiated types. The code, I believe, clarify. Note, it's not

#include <iostream>

template<typename T>
struct Templ
T some_dummy_value;

class A{};
class B{};

struct InstanceA
Templ<A> inst;
void foo(){}

struct InstanceB
Templ<B> inst;
void foo(){}

//here the question
struct Counter
// ???????????
INSTANCES_NUM = // ????????

int main()
// I need this value _before_ creating any objects of
// instantiated types.
std::cout << Counter::INSTANCES_NUM << std::endl;

// And only now (!) create instances of InstanceA, InstanceB
InstanceA a;;
InstanceB b;;

As you see I need number of instantiation before creating any objects
of instantiated types, so it's almost (at least i see so) the same as
knowing at compile time, so i wrote

enum { INSTANCE_NUM };

The reasoning. What I wrote above is extraction of what I need for
simpleness and clearness. The real problem.
I recently wrote a wrapper for plain C written simulation system (SS)
designed with performance issues in mind, E.G. data locality. So i
chose to use template-based approach for wrapping. This discrete
event-driven SS managed memory itself and asks me for maximum size of
messages _IT_ will create for me. So i wrote wrapers, but now I need to
feed it with maximum message size of templates (==wraper for messages)
i created.

The flow.

#include <ss.h>

struct MsgA{};
struct MsgB{};

void fill_a( MsgA * msg ){}
void fill_b( MsgB * msg ){}

// callback for SS
void event_handler( void * msg ){}

// callback for SS
void init()
void * event = ss_create_event(time, recepient);
MsgA * msg = (MsgA*) ss_message_data(event);
fill_a( msg );
ss_send_msg( event );

// the same with msg B

SS_AgentType agent_type = {

int main()
agents_num = 10;
max_msg_size = max( sizeof( MsgA ) , sizeof( MsgB ) );

ss_init( agents_num, max_msg_size, agent_type );
// process results.

I wrote wrapper that (almost) statically dispatch agents and message
types and i avoided cast's from void *. But I still need to calculate
message sizes. I want to avoid it to. It's quite the same as calculate
number of instances.

BR, Ruslan Mullakhmetov

All times are GMT. The time now is 03:54 PM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.