Reputation: 9000
Consider the following example:
#include <iostream>
#include <type_traits>
inline void f()
{
std :: cout << "Welcome to f!" << std :: endl;
}
inline void g()
{
std :: cout << "Welcome to g!" << std :: endl;
}
inline void h()
{
std :: cout << "Welcome to h!" << std :: endl;
}
typedef void (*function)();
const function table[] = {f, g, h};
int main()
{
int idx;
std :: cin >> idx;
table[idx]();
}
Here I have three functions, f
, g
and h
. I put their pointers into a const
array. Then, at runtime, I ask my user to provide a number and the corresponding function in the table is called.
I guess this is not going to get inlined, am I correct? I tried to inspect the assembly code but I really suck at reading assembly.
So I wonder, do I have better options to get the call to either f
, g
and h
inlined? I mean, if I were to just make a switch this would work flawlessly.
Note: this is just an example, in a real-world scenario I will have a set of functions, known at compile time but determined by a kinda lengthy procedure. So I am not able to just, e.g., write the code in a switch statement.
Upvotes: 0
Views: 65
Reputation: 3068
Provided you make use of proper const expressions, it is guaranteed that the code will be inlined at compile time. Have a look at the conditionals for that in this thread: When does a constexpr function get evaluated at compile time?
Upvotes: 0