I'll provide a clean solution for dispatching to the correct template instantiation based on a runtime enum value. This approach eliminates any manual if/else statements at the call site.
// Assuming your enum is defined like this:
enum class MyEnum {
Value1,
Value2,
// potentially more values...
};
// And your template and function are defined like:
template<MyEnum E>
struct T {
// implementation details
};
template<typename TType>
void funcaboba() {
// implementation
}
// Here's the dispatcher solution:
template<template<MyEnum> class TTemplate>
inline void dispatch_funcaboba(MyEnum enum_value) {
// Create a table of function pointers at compile time
static constexpr auto dispatch_table = []() {
using FuncPtr = void(*)();
std::array<FuncPtr, 2> table{}; // Size matches number of enum values
table[static_cast<size_t>(MyEnum::Value1)] = &funcaboba<TTemplate<MyEnum::Value1>>;
table[static_cast<size_t>(MyEnum::Value2)] = &funcaboba<TTemplate<MyEnum::Value2>>;
// Add more entries if you have more enum values
return table;
}();
// Call the appropriate function through the table
dispatch_table[static_cast<size_t>(enum_value)]();
}
// Usage:
void your_function(SomeType* typedPtr) {
// Single line call, no manual if/else:
dispatch_funcaboba<T>(typedPtr->selfType);
}
This solution:
- Creates a compile-time function pointer table mapping each enum value to its corresponding template instantiation
- Provides a clean one-line call site with no visible conditionals
- Has minimal runtime overhead (just an array lookup and function call)
- Works with any number of enum values by extending the table
If your enum values aren't consecutive starting from 0, you can use a slightly modified approach with a switch statement inside the dispatcher (still hidden from your call site):
template<template<MyEnum> class TTemplate>
inline void dispatch_funcaboba(MyEnum enum_value) {
switch(enum_value) {
case MyEnum::Value1: funcaboba<TTemplate<MyEnum::Value1>>(); break;
case MyEnum::Value2: funcaboba<TTemplate<MyEnum::Value2>>(); break;
// Add more cases as needed
}
}
Both approaches achieve your goal of a clean single-line call with no manual conditionals while properly handling the compile-time template instantiation based on runtime values.