Templated structs / variant values

Marek Janukowicz marek at janukowicz.net
Wed Aug 14 15:29:36 PDT 2013


I need to have a generalized "settings" functionality that should work like 
this:
* I need to be able to add this to a class
* each setting has its name, description, type and default value
* I need to iterate over all settings for given object

API would more or less look like:
class A {
 ... here I somehow define a setting called "maxTime"
}

A a = new A();

auto b = a.settings["maxTime"].value; // b would contain default value, 
because it wasn't set explicitly yet
string s = a.settings["maxTime"].description; // s would contain setting 
description
a.settings["maxTime"].value = 10.seconds; // This would only work if maxTime 
setting is of type duration
foreach( name, value; a.settings ) ...

Now the problem that I have is with storing those settings. What I've come 
up with so far are either Variants or templated structs (either really 
templated and type parametrized structs returned from template functions). 
The problem with variants is that I don't know how to force the value to be 
of certain type (variant accepts anything). As for templates and structs I 
tried something like:

auto setting (string name, string description, T, T deflt)() {
  struct Setting {
    string name = name;
    T value;
  }
  return Setting(name, deflt);
}

but then I don't know if there is any way to build an array of those to be 
able to iterate over them.

I know generally there should be some kind of "setting definition" defined 
on class level that would keep shared information (like names and defaults) 
and then per-instance data containing just actual values, but I don't really 
care and any solution where this shared information is copied for every 
instance would also be fine.

I know the description above is a bit messy (it's quite late now), but 
hopefully you can get the picture. Any ideas how to approach this problem?

-- 
Marek Janukowicz


More information about the Digitalmars-d-learn mailing list