I’m looking for information on a pattern that I have used recently. The basic idea is that there is a type with a property that can either be compile-time (template parameter) or runtime (member). std::span is a good example of this pattern. Here is an example of the pattern in its purest form:
// sentinel value
constexpr int runtime = -1;
// compile-time version
template <int Property = runtime>
struct Type {
static constexpr int getProp() {
return Property;
}
};
// runtime version
template <>
struct Type<runtime> {
int getProp() const {
return property;
}
private:
int property;
};
template <typename T>
int square(T obj) {
// does a multiply if T is Type<runtime>
// otherwise returns a constant
return obj.getProp() * obj.getProp();
}
You usually end up with two very similar classes so I typically hoist common code up into a base class using the CRTP idiom.
- Does this pattern have a name?
- If there isn’t a good name, how should I describe it? (The title of the question is my best attempt)
- Has someone written about this pattern somewhere?
- When should I avoid using this pattern?