473,663 Members | 2,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamically choosing a template parameter at runtime

AFAIK a template parameter must be completely determinable by the
compiler at compile time, is this correct?

Currently my problem is, I have a class which contains a std::vector.
The size of this vector can be determined at the time an object of the
class is constructed, and is assured not to change over the lifetime
of the object.

Now this class is part of an intrusive memory pool management scheme,
and while it's okay for the std::vector to use standard allocations,
I'd prefer that the underlying array be part of the object, so that
the memory manager will handle the entire memory of that class,
instead of just (effectively) the pointer, size, and capacity.

//Generic is the intrusive memory pool
//management base class
class Closure : public Generic {
public:
....
Closure(size_t S) : dat(S) {}
std::vector<Gen eric*dat;
Generic*& operator[](size_t i){return dat[i]};
};

What I'd rather have:

class Closure : public Generic {
public:
....
virtual Generic*& operator[](size_t i)=0;
};

template<size_t S>
class ClosureA : public Closure{
public:
Generic* dat[S];
virtual Generic*& operator[](size_t i){return dat[i];};
};

However the size parameter must be determined at runtime, not compile
time:

// current use!
void do_something(He ap& h, size_t N){
Closure *s = new(h) Closure(N);
....
}

The best solution I could come up with is:

// fallback on vectors
class ClosureV : public Closure{
public:
ClosureV(size_t S) : dat(S){}
std::vector<Gen eric*dat;
virtual Generic*& operator[](size_t i){return dat[i];};
};

//factory function
Closure* NewClosure(Heap & h,size_t S){
switch(S){
case 0: return new(h) ClosureA<0>();
case 1: return new(h) ClosureA<1>();
case 2: return new(h) ClosureA<2>();
case 3: return new(h) ClosureA<3>();
case 4: return new(h) ClosureA<4>();
case 5: return new(h) ClosureA<5>();
case 6: return new(h) ClosureA<6>();
case 7: return new(h) ClosureA<7>();
case 8: return new(h) ClosureA<8>();
// give up; not likely to occur, but still might... :(
default: return new(h) ClosureV(S);
}
}

I'd like to ask if there's a better way?
Jul 24 '08 #1
4 7939
On 24 jul, 03:15, alan <almkg...@gmail .comwrote:
AFAIK a template parameter must be completely determinable by the
compiler at compile time, is this correct?
Yes, it's correct.
Currently my problem is, I have a class which contains a std::vector.
The size of this vector can be determined at the time an object of the
class is constructed, and is assured not to change over the lifetime
of the object.

Now this class is part of an intrusive memory pool management scheme,
and while it's okay for the std::vector to use standard allocations,
I'd prefer that the underlying array be part of the object, so that
the memory manager will handle the entire memory of that class,
instead of just (effectively) the pointer, size, and capacity.

//Generic is the intrusive memory pool
//management base class
class Closure : public Generic {
public:
* * * * ....
* * * * Closure(size_t S) : dat(S) {}
* * * * std::vector<Gen eric*dat;
* * * * Generic*& operator[](size_t i){return dat[i]};

};

What I'd rather have:

class Closure : public Generic {
public:
* * * * ....
* * * * virtual Generic*& operator[](size_t i)=0;

};

template<size_t S>
class ClosureA : public Closure{
public:
* * * * Generic* dat[S];
* * * * virtual Generic*& operator[](size_t i){return dat[i];};

};

However the size parameter must be determined at runtime, not compile
time:

// current use!
void do_something(He ap& h, size_t N){
* * * * *Closure *s = new(h) Closure(N);
* * * * *....

}

The best solution I could come up with is:

// fallback on vectors
class ClosureV : public Closure{
public:
* * * * ClosureV(size_t S) : dat(S){}
* * * * std::vector<Gen eric*dat;
* * * * virtual Generic*& operator[](size_t i){return dat[i];};

};

//factory function
Closure* NewClosure(Heap & h,size_t S){
* * * * switch(S){
* * * * case 0: return new(h) ClosureA<0>();
* * * * case 1: return new(h) ClosureA<1>();
* * * * case 2: return new(h) ClosureA<2>();
* * * * case 3: return new(h) ClosureA<3>();
* * * * case 4: return new(h) ClosureA<4>();
* * * * case 5: return new(h) ClosureA<5>();
* * * * case 6: return new(h) ClosureA<6>();
* * * * case 7: return new(h) ClosureA<7>();
* * * * case 8: return new(h) ClosureA<8>();
* * * * // give up; not likely to occur, but still might... :(
* * * * default: return new(h) ClosureV(S);
* * * * }

}

I'd like to ask if there's a better way?

Templates are compile-time mechanisms. On the other hand, virtual
stuff are run-time mechanisms. (That's why a template function cannot
be virtual.) I suggest you to write this classes using either
templates or virtuals, not mixing them. If you want to stick with the
dynamic world, std::vector is a choice, just as you did.

Keep in mind that with templates you can almost always achieve the
same functionality of dynamic polimorphism with techniques that allow
you to design static polimorphism. You loose the ability to create
heterogeneous collections (or similars), but there's usually some
workaround. However, there other benefits like, for example,
performance gains.

--
Leandro T. C. Melo
Jul 24 '08 #2
On Jul 24, 5:15*pm, alan <almkg...@gmail .comwrote:
AFAIK a template parameter must be completely determinable by the
compiler at compile time, is this correct?
Yes.
>
I'd like to ask if there's a better way?
That's a pretty good way and most likely just fine.

There is a way to use a generic factory pattern to do the same thing
but one can debate if it's worth the trouble. You will still need to
register all the sizes you care for.

Jul 25 '08 #3
I'd like to ask if there's a better way?
>
That's a pretty good way and most likely just fine.

There is a way to use a generic factory pattern to do the same thing
but one can debate if it's worth the trouble. *You will still need to
register all the sizes you care for.
Err, I thought what I already did was a factory pattern?

Or is "generic factory pattern" something even more than what I just
did??

Jul 25 '08 #4
On Jul 24, 7:41*pm, Leandro Melo <ltcm...@gmail. comwrote:
>
I'd like to ask if there's a better way?

Templates are compile-time mechanisms. On the other hand, virtual
stuff are run-time mechanisms. (That's why a template function cannot
be virtual.) I suggest you to write this classes using either
templates or virtuals, not mixing them. If you want to stick with the
dynamic world, std::vector is a choice, just as you did.
None of the virtual functions are templated. The template I'm using
is a size template, since I would like to make a class with a variable-
size array, which I'd prefer to be part of the class object.

And std::vector isn't so good a choice: it allocates using the default
allocator. I know it can use a different allocator, the problem is
that my memory manager is intrusive, so std::vector will have to
allocate a class that ultimately derives from Generic, my intrusive
class. But std::vector allocates a plain memory area, which my
intrusive memory manager cannot handle.

The main reason I'm mixing templates and virtuals is that I need my
class to be variable size, but still present the same interface, i.e.
the Closure interface.
Jul 25 '08 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3914
by: Sebastian Faust | last post by:
Hi, I have 4 questions related to templates. I wanna do something like the following: template<typename T> class Template { public: Template_Test<T>()
20
12879
by: David | last post by:
I have a one-line script to add an onunload event handler to the body of the document. The script is as follows: document.getElementsByTagName("BODY").onunload=function s() {alert("s")} Now obviously, I put the alert("s") part in for debugging purposes, just to make sure the error wasn't in any code I was going to be running. This line works just fine in IE6 but in Firefox it doesn't. However, if I replace that line with the...
4
2722
by: wkaras | last post by:
I would like to propose the following changes to the C++ Standard, the goal of which are to provide an improved ability to specify the constraints on type parameters to templates. Let me say from the start that my knowledge of compiler implementation is very limited. Therefore, my suggestions may have to be rejected because they are difficult or impossible to implement. The proposal is based on the concept of "type similarity". Type...
4
1802
by: Robert | last post by:
Are there any other ways to dynamically apply CSS styling to a page (without using inline CSS)? I'm sure I could dynamically generate a new and uniquely named CSS file "on the fly" when users log in, and then dynamically associate that css file with the requested pages - but I'm looking for something much simpler and with better runtime performance. Here's what I'm after. I plan to let users save various preferences between sessions....
2
1432
by: Suma | last post by:
I have a problem with editable datagrid and was hoping if anyone could help me. Please help me if possible. I have an editable datagrid, whose column count I don’t know until runtime. I am sure of 3 columns Id,Name and Description. But there also might be more. So I add these 3 columns and an editcommandbutton and deletecommnadbutton at design time. Then during runtime I insert my other columns that I need, in between
1
3407
by: Marcus | last post by:
I have a problem maybe one of you could help me with. I've created a data entry screen with lots of dynamically-created client-side controls. I create HTML texboxes client-side by assigning a value to the td.innerHTML property. The UI is done, and I now want to post back the user's changes and update my business object in .NET. But when I postback, I can't see any of my dynamically created HTML controls in VB .NET. How do I make them...
25
2138
by: David Sanders | last post by:
Hi, As part of a simulation program, I have several different model classes, ModelAA, ModelBB, etc., which are all derived from the class BasicModel by inheritance. model to use, for example if the parameter model_name is "aa", then choose ModelAA. Currently I do this as follows:
5
2529
by: Wayne Shu | last post by:
Hi, guys I am reading Vandevoorde and Josuttis 's "C++ Template The Complete Guide" these days. When I read the chapter 15: Traits and Policy classes. I copy the code in 15.2.2 that use to determining the class type. The code is below:
4
2365
by: David Sanders | last post by:
Hi, I have a class depending on a template parameter: template<int n> class MyClass { }; I want the template parameter to be chosen according to a variable, e.g.
0
8768
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8547
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8633
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7368
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5655
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4181
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4348
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2763
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1754
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.