Template shenannigans with multiple datatypes

Chris Katko ckatko at gmail.com
Fri May 13 06:43:39 UTC 2022


I have an intrinsicGraph(T) class that is given a pointer to a T 
dataSource and automatically polls that variable every frame to 
add it to the graph, whether it's a float, double, integer, and 
maybe bool.

This all works fine if you have a single template type. But what 
if I want ... multiple graphs? I cannot do
````D
class intrinsicGraph(T???)
{
(void*) dataSources[];
}
````
and have it become whatever datatype I want. Even if I'm always 
storing the values in a float buffer, the dataSources themselves 
cannot be multiple types.

Basically I'm wondering if there's a way to have
````D
int FPS;
float frameTime;
//
graph myGraph;
myGraph.add(&frameTime);
myGraph.add(&fps);
````
and it enumerates through its dataSources array and adds to the 
relevant buffers.

There is a key that might help, they're all types that can 
resolve to integer or float. I'm not trying to add support for 
adding myRandomClass or networkPacket. Only things that can 
resolve down to float in some form.

Is there some kind of clue in having an array of Object (the 
fundamental superclass?)?

I don't think this is necessarily a "run time" reflection 
problem. Because I could make a graph at compile time, and know 
its of type, say, (T V U). Say, float, double, uint. Some sort of 
vardiac template.

But then how would you store that, unless you use some sort of 
mixins to write separate variables. (float\* dataSource0 and 
double\* dataSource1)

Or, wrap each pointer in some sort of fat pointer class that 
stores the type and a void*, and have an array of those fat 
pointers and and use some compile time voodoo to cast back  
cast(float)dataSource[0] (zero is always float), 
cast(uint)dataSource[2] (index 2 has cast(uint) put in).

Additional questions:

This may sound strange but is there a way to avoid having to 
specify the template type twice?
```D
instrinsicGraph!float testGraph;
instrinsicGraph!ulong testGraph2;
// later
testGraph = new intrinsic_graph!float(units[0].x, 100, 300, 
COLOR(1,0,0,1));
testGraph2 = new intrinsic_graph!ulong(g.stats.fps, 100, 500, 
COLOR(1,0,0,1));
```
It'd be nice if I only had to specify the type once.

It'd also be kinda nice if I could hide the fact I need to 
specify the type at all and have it automatically become whatever 
type the passed in value is:

````D
instrinsicGraph testGraph(g.stats.fps) //automatically stores an 
integer buffer.
````





More information about the Digitalmars-d-learn mailing list