Consider the following code that generically creates a dispatch table with a maximum size and then dispatches based on a runtime index:
#include <utility>template <class D, std::size_t... I> auto dispatch(std::size_t i, std::index_sequence<I...>) { using F = decltype(&D::template dispatch<0>); static constexpr F table[sizeof...(I)] = {&D::template dispatch<I>...}; return table[i]();}template <class D, std::size_t MAX_SIZE> auto dispatch(std::size_t i) { return dispatch<D>(i, std::make_index_sequence<MAX_SIZE>());}struct Dispatcher { template <std::size_t I> static auto dispatch() { return 42; }};auto foo(std::size_t i) { constexpr std::size_t MAX_SIZE = 10; if (i < MAX_SIZE) { return dispatch<Dispatcher, MAX_SIZE>(i); } return 0;}
Both GCC 14.1 and Clang 18.1 with optimization level -O3
will generate code for 10 identical functions and then dispatch dynamically. Is there a way I can make GCC or Clang recognize that these functions are identical and optimize the dynamic dispatch away? For my use case the dispatch
function is part of a library that might be called in different ways and I would like the compiler to optimize the dispatch if all the functions in the table are identical and only generate the table and dispatch if they are not identical.