Code reuse: compile-time decisions based on attributes of generic types
-
Is it possible to write code to make compile-time decisions about which code to include, depending on attributes (or the presence of) generic parameters of the class? For example:
class HashTable<TKey,optional TValue> { ... struct Slot { public TKey Key; #if present(TValue) public TValue Value; #endif } }
When TValue is present, the hash table would behave like a normal hash table; when TValue is not present, the hash table would behave like a set. The difference between a set and a hash table is very minor and it would be error-prone and inelegant to have to duplicate the entire class to get both a set and hash table from code that, with very little modification, could support both. Something like this might be feasible too (the semantics here with SpecialTValue are problematic; this example is just to illustrate the idea):class HTBase<TKey,TValue> { ... struct Slot { public TKey Key; #if (TValue is SpecialTValue) public TValue Value; #endif } } class HashTable<TKey,TValue> : HTBase<TKey,TValue> class Set<TKey> : HTBase<TKey,SpecialTValue>