In C++ I basically have two choices in policy based design patterns: I can use individual types (based on which an overload is selected) or specify an enum that contains all policies and I would dispatch over them at runtime. What is the preferred way of writing policy based design nowadays?
#include <cstdio>
/* Policy using types */
namespace type_policy
{
struct detached_t{};
struct deferred_t{};
inline constexpr detached_t detached = detached_t{};
inline constexpr deferred_t deferred = deferred_t{};
}
auto do_something(type_policy::detached_t pol)
{
printf("detached type policy selected\n");
}
auto do_something(type_policy::deferred_t pol)
{
printf("deferred type policy selected\n");
}
/* Policy using enums */
enum class enum_policy
{
detached,
deferred,
};
static auto do_something_else(const enum_policy pol)
{
if (pol == enum_policy::deferred) {
printf("deferred enum policy selected\n");
} else {
printf("detached enum policy selected\n");
}
}
int main()
{
do_something(type_policy::deferred);
do_something_else(enum_policy::detached);
}
Note: When the enum dispatch is built into a static function, the compiler is able to eliminate the conditional at compile time as well. It is also less verbose from the start... should it be the preferred way?