How to avoid run-time checks for running parts of code that become unreachable after compilation? The Next CEO of Stack OverflowHow can I profile C++ code running on Linux?Counting the total of same running processes in C++Usage of this next_combination codeIdentify objects in boost::shared_ptr<boost::thread>How C++ reference worksNamespaces and the Pre-Processorstd::atomic_is_lock_free(shared_ptr<T>*) didn't compileCleaning data after exception on class constructorTwo-level bind fails on GCC/libstdc++ and Clang/libc++How do i read bool value using std::istream

Does the Idaho Potato Commission associate potato skins with healthy eating?

Is the offspring between a demon and a celestial possible? If so what is it called and is it in a book somewhere?

Could you use a laser beam as a modulated carrier wave for radio signal?

Is it possible to create a QR code using text?

Masking layers by a vector polygon layer in QGIS

Can you teleport closer to a creature you are Frightened of?

Is it "common practice in Fourier transform spectroscopy to multiply the measured interferogram by an apodizing function"? If so, why?

How exploitable/balanced is this homebrew spell: Spell Permanency?

Upgrading From a 9 Speed Sora Derailleur?

My boss doesn't want me to have a side project

Direct Implications Between USA and UK in Event of No-Deal Brexit

How seriously should I take size and weight limits of hand luggage?

Ising model simulation

Incomplete cube

Identify and count spells (Distinctive events within each group)

Calculate the Mean mean of two numbers

Arity of Primitive Recursive Functions

Is it okay to majorly distort historical facts while writing a fiction story?

Free fall ellipse or parabola?

Oldie but Goldie

Is a distribution that is normal, but highly skewed, considered Gaussian?

Why did early computer designers eschew integers?

Mathematica command that allows it to read my intentions

Which acid/base does a strong base/acid react when added to a buffer solution?



How to avoid run-time checks for running parts of code that become unreachable after compilation?



The Next CEO of Stack OverflowHow can I profile C++ code running on Linux?Counting the total of same running processes in C++Usage of this next_combination codeIdentify objects in boost::shared_ptr<boost::thread>How C++ reference worksNamespaces and the Pre-Processorstd::atomic_is_lock_free(shared_ptr<T>*) didn't compileCleaning data after exception on class constructorTwo-level bind fails on GCC/libstdc++ and Clang/libc++How do i read bool value using std::istream










7















My program gets a couple of Boolean variables from the user, and their values won't change afterwards. Each Boolean variable enables a part of code. Something like this:



#include <iostream>

void callback_function(bool task_1, bool task_2, bool task_3)
if (task_1)
std::cout << "Running task 1" << std::endl;

if (task_2)
std::cout << "Running task 2" << std::endl;

if (task_3)
std::cout << "Running task 3" << std::endl;



int main()
bool task_1 = true;
bool task_2 = false;
bool task_3 = true;

while (true)
callback_function(task_1, task_2, task_3);


return 0;



Now my question is, since the Boolean variables are fixed every time the program calls callback_function(), is there a way to avoid the if statements inside the callback function?



This is one way to avoid the run-time checks (implement a callback function for all permutations of the Boolean variables --- only two cases are shown below):



#include <functional>
#include <iostream>

void callback_function_for_tasks_1_2_3()
std::cout << "Running task 1" << std::endl;
std::cout << "Running task 2" << std::endl;
std::cout << "Running task 3" << std::endl;


void callback_function_for_tasks_1_3()
std::cout << "Running task 1" << std::endl;
std::cout << "Running task 3" << std::endl;


int main()
bool task_1 = true;
bool task_2 = false;
bool task_3 = true;

std::function<void()> callback_function;
if (task_1 && task_2 && task_3)
callback_function = callback_function_for_tasks_1_2_3;
else if (task_1 && !task_2 && task_3)
callback_function = callback_function_for_tasks_1_3;


while (true)
callback_function();


return 0;



The problem is I have to implement 2^n different callback functions, if there are n Boolean variables. Is there a better way to accomplish this?










share|improve this question







New contributor




Alireza Shafaei is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 6





    If you’re interested in performance, don’t use std::function when a function pointer will do.

    – Davis Herring
    yesterday






  • 5





    Have you actually measured whether these conditional statements make a difference? This looks like a pretty pointless optimization effort to me. Or, if you're trying to solve an actual problem with this, it may be the wrong approach, a so-called "XY problem". Please, as a new user, also take the tour and read How to Ask.

    – Ulrich Eckhardt
    yesterday











  • If you go with with the 2nd approach, I believe, you will end up doing more checks then the 1st approch. Because each compound checks you are doing in the 2nd one will computationally cost you more than the 1st. I am not sure what are you trying to accomplish here, but if your concern is that for a false flag, the statements inside the block will take time to execute, then you don't have to worry about that. Because if the flag is false, the block will not take any execution time. And checking 1 by 1 will be cheaper than the combinations.

    – ABM Ruman
    yesterday







  • 2





    @ABMRuman He'd be doing more checks only once, not every time in the loop. If this is a long running application... One could safe quite a lot of checks if one combined the conditions inside an unsigned int/uint32_t/uint64_t (depending on number of checks) and select the function via a switch statement. The functions might be generated via a template function using if constexpr inside, so one wouldn't need to write all the functions explicitly.

    – Aconcagua
    yesterday











  • Joining @UlrichEckhardt: You should first run a profiler to find the hottest spots to optimise. Optimising the called functions at the right places will most likely bring you much more performance gain than avoiding these view ifs...

    – Aconcagua
    yesterday















7















My program gets a couple of Boolean variables from the user, and their values won't change afterwards. Each Boolean variable enables a part of code. Something like this:



#include <iostream>

void callback_function(bool task_1, bool task_2, bool task_3)
if (task_1)
std::cout << "Running task 1" << std::endl;

if (task_2)
std::cout << "Running task 2" << std::endl;

if (task_3)
std::cout << "Running task 3" << std::endl;



int main()
bool task_1 = true;
bool task_2 = false;
bool task_3 = true;

while (true)
callback_function(task_1, task_2, task_3);


return 0;



Now my question is, since the Boolean variables are fixed every time the program calls callback_function(), is there a way to avoid the if statements inside the callback function?



This is one way to avoid the run-time checks (implement a callback function for all permutations of the Boolean variables --- only two cases are shown below):



#include <functional>
#include <iostream>

void callback_function_for_tasks_1_2_3()
std::cout << "Running task 1" << std::endl;
std::cout << "Running task 2" << std::endl;
std::cout << "Running task 3" << std::endl;


void callback_function_for_tasks_1_3()
std::cout << "Running task 1" << std::endl;
std::cout << "Running task 3" << std::endl;


int main()
bool task_1 = true;
bool task_2 = false;
bool task_3 = true;

std::function<void()> callback_function;
if (task_1 && task_2 && task_3)
callback_function = callback_function_for_tasks_1_2_3;
else if (task_1 && !task_2 && task_3)
callback_function = callback_function_for_tasks_1_3;


while (true)
callback_function();


return 0;



The problem is I have to implement 2^n different callback functions, if there are n Boolean variables. Is there a better way to accomplish this?










share|improve this question







New contributor




Alireza Shafaei is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.















  • 6





    If you’re interested in performance, don’t use std::function when a function pointer will do.

    – Davis Herring
    yesterday






  • 5





    Have you actually measured whether these conditional statements make a difference? This looks like a pretty pointless optimization effort to me. Or, if you're trying to solve an actual problem with this, it may be the wrong approach, a so-called "XY problem". Please, as a new user, also take the tour and read How to Ask.

    – Ulrich Eckhardt
    yesterday











  • If you go with with the 2nd approach, I believe, you will end up doing more checks then the 1st approch. Because each compound checks you are doing in the 2nd one will computationally cost you more than the 1st. I am not sure what are you trying to accomplish here, but if your concern is that for a false flag, the statements inside the block will take time to execute, then you don't have to worry about that. Because if the flag is false, the block will not take any execution time. And checking 1 by 1 will be cheaper than the combinations.

    – ABM Ruman
    yesterday







  • 2





    @ABMRuman He'd be doing more checks only once, not every time in the loop. If this is a long running application... One could safe quite a lot of checks if one combined the conditions inside an unsigned int/uint32_t/uint64_t (depending on number of checks) and select the function via a switch statement. The functions might be generated via a template function using if constexpr inside, so one wouldn't need to write all the functions explicitly.

    – Aconcagua
    yesterday











  • Joining @UlrichEckhardt: You should first run a profiler to find the hottest spots to optimise. Optimising the called functions at the right places will most likely bring you much more performance gain than avoiding these view ifs...

    – Aconcagua
    yesterday













7












7








7


1






My program gets a couple of Boolean variables from the user, and their values won't change afterwards. Each Boolean variable enables a part of code. Something like this:



#include <iostream>

void callback_function(bool task_1, bool task_2, bool task_3)
if (task_1)
std::cout << "Running task 1" << std::endl;

if (task_2)
std::cout << "Running task 2" << std::endl;

if (task_3)
std::cout << "Running task 3" << std::endl;



int main()
bool task_1 = true;
bool task_2 = false;
bool task_3 = true;

while (true)
callback_function(task_1, task_2, task_3);


return 0;



Now my question is, since the Boolean variables are fixed every time the program calls callback_function(), is there a way to avoid the if statements inside the callback function?



This is one way to avoid the run-time checks (implement a callback function for all permutations of the Boolean variables --- only two cases are shown below):



#include <functional>
#include <iostream>

void callback_function_for_tasks_1_2_3()
std::cout << "Running task 1" << std::endl;
std::cout << "Running task 2" << std::endl;
std::cout << "Running task 3" << std::endl;


void callback_function_for_tasks_1_3()
std::cout << "Running task 1" << std::endl;
std::cout << "Running task 3" << std::endl;


int main()
bool task_1 = true;
bool task_2 = false;
bool task_3 = true;

std::function<void()> callback_function;
if (task_1 && task_2 && task_3)
callback_function = callback_function_for_tasks_1_2_3;
else if (task_1 && !task_2 && task_3)
callback_function = callback_function_for_tasks_1_3;


while (true)
callback_function();


return 0;



The problem is I have to implement 2^n different callback functions, if there are n Boolean variables. Is there a better way to accomplish this?










share|improve this question







New contributor




Alireza Shafaei is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.












My program gets a couple of Boolean variables from the user, and their values won't change afterwards. Each Boolean variable enables a part of code. Something like this:



#include <iostream>

void callback_function(bool task_1, bool task_2, bool task_3)
if (task_1)
std::cout << "Running task 1" << std::endl;

if (task_2)
std::cout << "Running task 2" << std::endl;

if (task_3)
std::cout << "Running task 3" << std::endl;



int main()
bool task_1 = true;
bool task_2 = false;
bool task_3 = true;

while (true)
callback_function(task_1, task_2, task_3);


return 0;



Now my question is, since the Boolean variables are fixed every time the program calls callback_function(), is there a way to avoid the if statements inside the callback function?



This is one way to avoid the run-time checks (implement a callback function for all permutations of the Boolean variables --- only two cases are shown below):



#include <functional>
#include <iostream>

void callback_function_for_tasks_1_2_3()
std::cout << "Running task 1" << std::endl;
std::cout << "Running task 2" << std::endl;
std::cout << "Running task 3" << std::endl;


void callback_function_for_tasks_1_3()
std::cout << "Running task 1" << std::endl;
std::cout << "Running task 3" << std::endl;


int main()
bool task_1 = true;
bool task_2 = false;
bool task_3 = true;

std::function<void()> callback_function;
if (task_1 && task_2 && task_3)
callback_function = callback_function_for_tasks_1_2_3;
else if (task_1 && !task_2 && task_3)
callback_function = callback_function_for_tasks_1_3;


while (true)
callback_function();


return 0;



The problem is I have to implement 2^n different callback functions, if there are n Boolean variables. Is there a better way to accomplish this?







c++






share|improve this question







New contributor




Alireza Shafaei is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question







New contributor




Alireza Shafaei is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question






New contributor




Alireza Shafaei is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked yesterday









Alireza ShafaeiAlireza Shafaei

362




362




New contributor




Alireza Shafaei is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Alireza Shafaei is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Alireza Shafaei is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.







  • 6





    If you’re interested in performance, don’t use std::function when a function pointer will do.

    – Davis Herring
    yesterday






  • 5





    Have you actually measured whether these conditional statements make a difference? This looks like a pretty pointless optimization effort to me. Or, if you're trying to solve an actual problem with this, it may be the wrong approach, a so-called "XY problem". Please, as a new user, also take the tour and read How to Ask.

    – Ulrich Eckhardt
    yesterday











  • If you go with with the 2nd approach, I believe, you will end up doing more checks then the 1st approch. Because each compound checks you are doing in the 2nd one will computationally cost you more than the 1st. I am not sure what are you trying to accomplish here, but if your concern is that for a false flag, the statements inside the block will take time to execute, then you don't have to worry about that. Because if the flag is false, the block will not take any execution time. And checking 1 by 1 will be cheaper than the combinations.

    – ABM Ruman
    yesterday







  • 2





    @ABMRuman He'd be doing more checks only once, not every time in the loop. If this is a long running application... One could safe quite a lot of checks if one combined the conditions inside an unsigned int/uint32_t/uint64_t (depending on number of checks) and select the function via a switch statement. The functions might be generated via a template function using if constexpr inside, so one wouldn't need to write all the functions explicitly.

    – Aconcagua
    yesterday











  • Joining @UlrichEckhardt: You should first run a profiler to find the hottest spots to optimise. Optimising the called functions at the right places will most likely bring you much more performance gain than avoiding these view ifs...

    – Aconcagua
    yesterday












  • 6





    If you’re interested in performance, don’t use std::function when a function pointer will do.

    – Davis Herring
    yesterday






  • 5





    Have you actually measured whether these conditional statements make a difference? This looks like a pretty pointless optimization effort to me. Or, if you're trying to solve an actual problem with this, it may be the wrong approach, a so-called "XY problem". Please, as a new user, also take the tour and read How to Ask.

    – Ulrich Eckhardt
    yesterday











  • If you go with with the 2nd approach, I believe, you will end up doing more checks then the 1st approch. Because each compound checks you are doing in the 2nd one will computationally cost you more than the 1st. I am not sure what are you trying to accomplish here, but if your concern is that for a false flag, the statements inside the block will take time to execute, then you don't have to worry about that. Because if the flag is false, the block will not take any execution time. And checking 1 by 1 will be cheaper than the combinations.

    – ABM Ruman
    yesterday







  • 2





    @ABMRuman He'd be doing more checks only once, not every time in the loop. If this is a long running application... One could safe quite a lot of checks if one combined the conditions inside an unsigned int/uint32_t/uint64_t (depending on number of checks) and select the function via a switch statement. The functions might be generated via a template function using if constexpr inside, so one wouldn't need to write all the functions explicitly.

    – Aconcagua
    yesterday











  • Joining @UlrichEckhardt: You should first run a profiler to find the hottest spots to optimise. Optimising the called functions at the right places will most likely bring you much more performance gain than avoiding these view ifs...

    – Aconcagua
    yesterday







6




6





If you’re interested in performance, don’t use std::function when a function pointer will do.

– Davis Herring
yesterday





If you’re interested in performance, don’t use std::function when a function pointer will do.

– Davis Herring
yesterday




5




5





Have you actually measured whether these conditional statements make a difference? This looks like a pretty pointless optimization effort to me. Or, if you're trying to solve an actual problem with this, it may be the wrong approach, a so-called "XY problem". Please, as a new user, also take the tour and read How to Ask.

– Ulrich Eckhardt
yesterday





Have you actually measured whether these conditional statements make a difference? This looks like a pretty pointless optimization effort to me. Or, if you're trying to solve an actual problem with this, it may be the wrong approach, a so-called "XY problem". Please, as a new user, also take the tour and read How to Ask.

– Ulrich Eckhardt
yesterday













If you go with with the 2nd approach, I believe, you will end up doing more checks then the 1st approch. Because each compound checks you are doing in the 2nd one will computationally cost you more than the 1st. I am not sure what are you trying to accomplish here, but if your concern is that for a false flag, the statements inside the block will take time to execute, then you don't have to worry about that. Because if the flag is false, the block will not take any execution time. And checking 1 by 1 will be cheaper than the combinations.

– ABM Ruman
yesterday






If you go with with the 2nd approach, I believe, you will end up doing more checks then the 1st approch. Because each compound checks you are doing in the 2nd one will computationally cost you more than the 1st. I am not sure what are you trying to accomplish here, but if your concern is that for a false flag, the statements inside the block will take time to execute, then you don't have to worry about that. Because if the flag is false, the block will not take any execution time. And checking 1 by 1 will be cheaper than the combinations.

– ABM Ruman
yesterday





2




2





@ABMRuman He'd be doing more checks only once, not every time in the loop. If this is a long running application... One could safe quite a lot of checks if one combined the conditions inside an unsigned int/uint32_t/uint64_t (depending on number of checks) and select the function via a switch statement. The functions might be generated via a template function using if constexpr inside, so one wouldn't need to write all the functions explicitly.

– Aconcagua
yesterday





@ABMRuman He'd be doing more checks only once, not every time in the loop. If this is a long running application... One could safe quite a lot of checks if one combined the conditions inside an unsigned int/uint32_t/uint64_t (depending on number of checks) and select the function via a switch statement. The functions might be generated via a template function using if constexpr inside, so one wouldn't need to write all the functions explicitly.

– Aconcagua
yesterday













Joining @UlrichEckhardt: You should first run a profiler to find the hottest spots to optimise. Optimising the called functions at the right places will most likely bring you much more performance gain than avoiding these view ifs...

– Aconcagua
yesterday





Joining @UlrichEckhardt: You should first run a profiler to find the hottest spots to optimise. Optimising the called functions at the right places will most likely bring you much more performance gain than avoiding these view ifs...

– Aconcagua
yesterday












3 Answers
3






active

oldest

votes


















15














Ensuring that if statements are evaluated at compile time



C++17 introduces if constexpr, which does exactly this:



template<bool task_1, bool task_2, bool task_3>
void callback_function()
if constexpr (task_1)
std::cout << "Running task 1" << std::endl;

if constexpr (task_2)
std::cout << "Running task 2" << std::endl;

if constexpr (task_3)
std::cout << "Running task 3" << std::endl;




If you have optimizations enabled, if constexpr isn't necessary. Even if you use a regular if instead of if constexpr, because the bools are now templated, the compiler will be able to eliminate the if statements entirely, and just run the tasks. If you look at the assembly produced here, you'll see that even at -O1, there are no if statements in any of the callback functions.



We can now use callback_function directly as a function pointer, avoiding function<void()>:



int main() 
using callback_t = void(*)();
callback_t func = callback_function<true, false, true>;

// Do stuff with func



We can also name the bools by assigning them to constexpr variables:



int main() 
using callback_t = void(*)();
constexpr bool do_task1 = true;
constexpr bool do_task2 = false;
constexpr bool do_task3 = true;
callback_t func = callback_function<do_task1, do_task2, do_task3>;

// Do stuff with func



Automatically creating a lookup table of all possible callback functions



You mentioned choosing between different callback functions at runtime. We can do this pretty easily with a lookup table, and we can use templates to automatically create a lookup table of all possible callback functions.



The first step is to get a callback function from a particular index:



// void(*)() is ugly to type, so I alias it
using callback_t = void(*)();

// Unpacks the bits
template<size_t index>
constexpr auto getCallbackFromIndex() -> callback_t

constexpr bool do_task1 = (index & 4) != 0;
constexpr bool do_task2 = (index & 2) != 0;
constexpr bool do_task3 = (index & 1) != 0;
return callback_function<do_task1, do_task2, do_task3>;



Once we can do that, we can write a function to create a lookup table from a bunch of indexes. Our lookup table will just be a std::array.



// Create a std::array based on a list of flags
// See https://en.cppreference.com/w/cpp/utility/integer_sequence
// For more information
template<size_t... Indexes>
constexpr auto getVersionLookup(std::index_sequence<Indexes...>)
-> std::array<callback_t, sizeof...(Indexes)>

return getCallbackFromIndex<Indexes>()...;


// Makes a lookup table containing all 8 possible callback functions
constexpr auto callbackLookupTable =
getVersionLookup(std::make_index_sequence<8>());


Here, callbackLookupTable contains all 8 possible callback functions, where callbackLookupTable[i] expands the bits of i to get the callback. For example, if i == 6, then i's bits are 110 in binary, so



callbackLookupTable[6] is callback_function<true, true, false>



Using the lookup table at runtime



Using the lookup table is really simple. We can get an index from a bunch of bools by bitshifting:



callback_t getCallbackBasedOnTasks(bool task1, bool task2, bool task3) 
// Get the index based on bit shifting
int index = ((int)task1 << 2) + ((int)task2 << 1) + ((int)task3);
// return the correct callback
return callbackLookupTable[index];



Example demonstrating how to read in tasks



We can get the bools at runtime now, and just call getCallbackBasedOnTasks to get the correct callback



int main() 
bool t1, t2, t3;
// Read in bools
std::cin >> t1 >> t2 >> t3;
// Get the callback
callback_t func = getCallbackBasedOnTasks(t1, t2, t3);
// Invoke the callback
func();






share|improve this answer

























  • The constexpr is IMHO a red herring, the important part is the use of template parameters which are evaluated at compile time. Any halfway-decent compiler is able to figure this out even without these consexpr hints.

    – Ulrich Eckhardt
    yesterday












  • I updated the answer explaining how to automatically generate a list of all possible callback functions. You can find the right one just by packing the bools into the bits of the index

    – Jorge Perez
    yesterday












  • The lookup table is a runtime solution. You can get the right function just by indexing into it

    – Jorge Perez
    yesterday











  • I added code showing exactly how to do that

    – Jorge Perez
    yesterday






  • 1





    (@$#*!) – can't find anything to criticise any more... Just kidding. But the automatically created lookup table is great, far better than my originally proposed switch statement...

    – Aconcagua
    yesterday



















1














Leave the code as it is.



Execution time of an "if" compared to writing to std::out is practically zero, so you are arguing over nothing. Well, unless you spend some time measuring the execution time as it is, and with the if's removed according to the values of the three constants, and found that there is a real difference.



At most, you might make the function inline or static, and the compiler will probably realise the arguments are always the same when optimisation is turned on. (My compiler would give a warning that you are using a function without a prototype, which means you should have either put a prototype into a header file, telling the compiler to expect calls from other call sites, or you should have made it static, telling the compiler that it knows all the calls and can use static analysis for optimisations).



And what you think is a constant, might not stay a constant forever. The original code will work. Any new code most likely won't.






share|improve this answer






























    0














    Short of JIT compilation, you can’t do better than your 2^n functions (and the resulting binary size). You can of course use a template to avoid writing them all out. To prevent the source from scaling exponentially just from selecting the correct implementation, you can write a recursive dispatcher (demo):



    template<bool... BB>
    auto g() return f<BB...>;
    template<bool... BB,class... TT>
    auto g(bool b,TT... tt)
    return b ? g<BB...,true>(tt...) : g<BB...,false>(tt...);





    share|improve this answer

























    • If you know something at compiletime, it's easy to template it. Especially in the OP's case.

      – Jorge Perez
      yesterday











    • @JorgePerez: I did say that you could use a template. I do realize now that you can put some of the ifs inside intermediate templates; I’ll edit that in.

      – Davis Herring
      yesterday











    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );






    Alireza Shafaei is a new contributor. Be nice, and check out our Code of Conduct.









    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55438306%2fhow-to-avoid-run-time-checks-for-running-parts-of-code-that-become-unreachable-a%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    15














    Ensuring that if statements are evaluated at compile time



    C++17 introduces if constexpr, which does exactly this:



    template<bool task_1, bool task_2, bool task_3>
    void callback_function()
    if constexpr (task_1)
    std::cout << "Running task 1" << std::endl;

    if constexpr (task_2)
    std::cout << "Running task 2" << std::endl;

    if constexpr (task_3)
    std::cout << "Running task 3" << std::endl;




    If you have optimizations enabled, if constexpr isn't necessary. Even if you use a regular if instead of if constexpr, because the bools are now templated, the compiler will be able to eliminate the if statements entirely, and just run the tasks. If you look at the assembly produced here, you'll see that even at -O1, there are no if statements in any of the callback functions.



    We can now use callback_function directly as a function pointer, avoiding function<void()>:



    int main() 
    using callback_t = void(*)();
    callback_t func = callback_function<true, false, true>;

    // Do stuff with func



    We can also name the bools by assigning them to constexpr variables:



    int main() 
    using callback_t = void(*)();
    constexpr bool do_task1 = true;
    constexpr bool do_task2 = false;
    constexpr bool do_task3 = true;
    callback_t func = callback_function<do_task1, do_task2, do_task3>;

    // Do stuff with func



    Automatically creating a lookup table of all possible callback functions



    You mentioned choosing between different callback functions at runtime. We can do this pretty easily with a lookup table, and we can use templates to automatically create a lookup table of all possible callback functions.



    The first step is to get a callback function from a particular index:



    // void(*)() is ugly to type, so I alias it
    using callback_t = void(*)();

    // Unpacks the bits
    template<size_t index>
    constexpr auto getCallbackFromIndex() -> callback_t

    constexpr bool do_task1 = (index & 4) != 0;
    constexpr bool do_task2 = (index & 2) != 0;
    constexpr bool do_task3 = (index & 1) != 0;
    return callback_function<do_task1, do_task2, do_task3>;



    Once we can do that, we can write a function to create a lookup table from a bunch of indexes. Our lookup table will just be a std::array.



    // Create a std::array based on a list of flags
    // See https://en.cppreference.com/w/cpp/utility/integer_sequence
    // For more information
    template<size_t... Indexes>
    constexpr auto getVersionLookup(std::index_sequence<Indexes...>)
    -> std::array<callback_t, sizeof...(Indexes)>

    return getCallbackFromIndex<Indexes>()...;


    // Makes a lookup table containing all 8 possible callback functions
    constexpr auto callbackLookupTable =
    getVersionLookup(std::make_index_sequence<8>());


    Here, callbackLookupTable contains all 8 possible callback functions, where callbackLookupTable[i] expands the bits of i to get the callback. For example, if i == 6, then i's bits are 110 in binary, so



    callbackLookupTable[6] is callback_function<true, true, false>



    Using the lookup table at runtime



    Using the lookup table is really simple. We can get an index from a bunch of bools by bitshifting:



    callback_t getCallbackBasedOnTasks(bool task1, bool task2, bool task3) 
    // Get the index based on bit shifting
    int index = ((int)task1 << 2) + ((int)task2 << 1) + ((int)task3);
    // return the correct callback
    return callbackLookupTable[index];



    Example demonstrating how to read in tasks



    We can get the bools at runtime now, and just call getCallbackBasedOnTasks to get the correct callback



    int main() 
    bool t1, t2, t3;
    // Read in bools
    std::cin >> t1 >> t2 >> t3;
    // Get the callback
    callback_t func = getCallbackBasedOnTasks(t1, t2, t3);
    // Invoke the callback
    func();






    share|improve this answer

























    • The constexpr is IMHO a red herring, the important part is the use of template parameters which are evaluated at compile time. Any halfway-decent compiler is able to figure this out even without these consexpr hints.

      – Ulrich Eckhardt
      yesterday












    • I updated the answer explaining how to automatically generate a list of all possible callback functions. You can find the right one just by packing the bools into the bits of the index

      – Jorge Perez
      yesterday












    • The lookup table is a runtime solution. You can get the right function just by indexing into it

      – Jorge Perez
      yesterday











    • I added code showing exactly how to do that

      – Jorge Perez
      yesterday






    • 1





      (@$#*!) – can't find anything to criticise any more... Just kidding. But the automatically created lookup table is great, far better than my originally proposed switch statement...

      – Aconcagua
      yesterday
















    15














    Ensuring that if statements are evaluated at compile time



    C++17 introduces if constexpr, which does exactly this:



    template<bool task_1, bool task_2, bool task_3>
    void callback_function()
    if constexpr (task_1)
    std::cout << "Running task 1" << std::endl;

    if constexpr (task_2)
    std::cout << "Running task 2" << std::endl;

    if constexpr (task_3)
    std::cout << "Running task 3" << std::endl;




    If you have optimizations enabled, if constexpr isn't necessary. Even if you use a regular if instead of if constexpr, because the bools are now templated, the compiler will be able to eliminate the if statements entirely, and just run the tasks. If you look at the assembly produced here, you'll see that even at -O1, there are no if statements in any of the callback functions.



    We can now use callback_function directly as a function pointer, avoiding function<void()>:



    int main() 
    using callback_t = void(*)();
    callback_t func = callback_function<true, false, true>;

    // Do stuff with func



    We can also name the bools by assigning them to constexpr variables:



    int main() 
    using callback_t = void(*)();
    constexpr bool do_task1 = true;
    constexpr bool do_task2 = false;
    constexpr bool do_task3 = true;
    callback_t func = callback_function<do_task1, do_task2, do_task3>;

    // Do stuff with func



    Automatically creating a lookup table of all possible callback functions



    You mentioned choosing between different callback functions at runtime. We can do this pretty easily with a lookup table, and we can use templates to automatically create a lookup table of all possible callback functions.



    The first step is to get a callback function from a particular index:



    // void(*)() is ugly to type, so I alias it
    using callback_t = void(*)();

    // Unpacks the bits
    template<size_t index>
    constexpr auto getCallbackFromIndex() -> callback_t

    constexpr bool do_task1 = (index & 4) != 0;
    constexpr bool do_task2 = (index & 2) != 0;
    constexpr bool do_task3 = (index & 1) != 0;
    return callback_function<do_task1, do_task2, do_task3>;



    Once we can do that, we can write a function to create a lookup table from a bunch of indexes. Our lookup table will just be a std::array.



    // Create a std::array based on a list of flags
    // See https://en.cppreference.com/w/cpp/utility/integer_sequence
    // For more information
    template<size_t... Indexes>
    constexpr auto getVersionLookup(std::index_sequence<Indexes...>)
    -> std::array<callback_t, sizeof...(Indexes)>

    return getCallbackFromIndex<Indexes>()...;


    // Makes a lookup table containing all 8 possible callback functions
    constexpr auto callbackLookupTable =
    getVersionLookup(std::make_index_sequence<8>());


    Here, callbackLookupTable contains all 8 possible callback functions, where callbackLookupTable[i] expands the bits of i to get the callback. For example, if i == 6, then i's bits are 110 in binary, so



    callbackLookupTable[6] is callback_function<true, true, false>



    Using the lookup table at runtime



    Using the lookup table is really simple. We can get an index from a bunch of bools by bitshifting:



    callback_t getCallbackBasedOnTasks(bool task1, bool task2, bool task3) 
    // Get the index based on bit shifting
    int index = ((int)task1 << 2) + ((int)task2 << 1) + ((int)task3);
    // return the correct callback
    return callbackLookupTable[index];



    Example demonstrating how to read in tasks



    We can get the bools at runtime now, and just call getCallbackBasedOnTasks to get the correct callback



    int main() 
    bool t1, t2, t3;
    // Read in bools
    std::cin >> t1 >> t2 >> t3;
    // Get the callback
    callback_t func = getCallbackBasedOnTasks(t1, t2, t3);
    // Invoke the callback
    func();






    share|improve this answer

























    • The constexpr is IMHO a red herring, the important part is the use of template parameters which are evaluated at compile time. Any halfway-decent compiler is able to figure this out even without these consexpr hints.

      – Ulrich Eckhardt
      yesterday












    • I updated the answer explaining how to automatically generate a list of all possible callback functions. You can find the right one just by packing the bools into the bits of the index

      – Jorge Perez
      yesterday












    • The lookup table is a runtime solution. You can get the right function just by indexing into it

      – Jorge Perez
      yesterday











    • I added code showing exactly how to do that

      – Jorge Perez
      yesterday






    • 1





      (@$#*!) – can't find anything to criticise any more... Just kidding. But the automatically created lookup table is great, far better than my originally proposed switch statement...

      – Aconcagua
      yesterday














    15












    15








    15







    Ensuring that if statements are evaluated at compile time



    C++17 introduces if constexpr, which does exactly this:



    template<bool task_1, bool task_2, bool task_3>
    void callback_function()
    if constexpr (task_1)
    std::cout << "Running task 1" << std::endl;

    if constexpr (task_2)
    std::cout << "Running task 2" << std::endl;

    if constexpr (task_3)
    std::cout << "Running task 3" << std::endl;




    If you have optimizations enabled, if constexpr isn't necessary. Even if you use a regular if instead of if constexpr, because the bools are now templated, the compiler will be able to eliminate the if statements entirely, and just run the tasks. If you look at the assembly produced here, you'll see that even at -O1, there are no if statements in any of the callback functions.



    We can now use callback_function directly as a function pointer, avoiding function<void()>:



    int main() 
    using callback_t = void(*)();
    callback_t func = callback_function<true, false, true>;

    // Do stuff with func



    We can also name the bools by assigning them to constexpr variables:



    int main() 
    using callback_t = void(*)();
    constexpr bool do_task1 = true;
    constexpr bool do_task2 = false;
    constexpr bool do_task3 = true;
    callback_t func = callback_function<do_task1, do_task2, do_task3>;

    // Do stuff with func



    Automatically creating a lookup table of all possible callback functions



    You mentioned choosing between different callback functions at runtime. We can do this pretty easily with a lookup table, and we can use templates to automatically create a lookup table of all possible callback functions.



    The first step is to get a callback function from a particular index:



    // void(*)() is ugly to type, so I alias it
    using callback_t = void(*)();

    // Unpacks the bits
    template<size_t index>
    constexpr auto getCallbackFromIndex() -> callback_t

    constexpr bool do_task1 = (index & 4) != 0;
    constexpr bool do_task2 = (index & 2) != 0;
    constexpr bool do_task3 = (index & 1) != 0;
    return callback_function<do_task1, do_task2, do_task3>;



    Once we can do that, we can write a function to create a lookup table from a bunch of indexes. Our lookup table will just be a std::array.



    // Create a std::array based on a list of flags
    // See https://en.cppreference.com/w/cpp/utility/integer_sequence
    // For more information
    template<size_t... Indexes>
    constexpr auto getVersionLookup(std::index_sequence<Indexes...>)
    -> std::array<callback_t, sizeof...(Indexes)>

    return getCallbackFromIndex<Indexes>()...;


    // Makes a lookup table containing all 8 possible callback functions
    constexpr auto callbackLookupTable =
    getVersionLookup(std::make_index_sequence<8>());


    Here, callbackLookupTable contains all 8 possible callback functions, where callbackLookupTable[i] expands the bits of i to get the callback. For example, if i == 6, then i's bits are 110 in binary, so



    callbackLookupTable[6] is callback_function<true, true, false>



    Using the lookup table at runtime



    Using the lookup table is really simple. We can get an index from a bunch of bools by bitshifting:



    callback_t getCallbackBasedOnTasks(bool task1, bool task2, bool task3) 
    // Get the index based on bit shifting
    int index = ((int)task1 << 2) + ((int)task2 << 1) + ((int)task3);
    // return the correct callback
    return callbackLookupTable[index];



    Example demonstrating how to read in tasks



    We can get the bools at runtime now, and just call getCallbackBasedOnTasks to get the correct callback



    int main() 
    bool t1, t2, t3;
    // Read in bools
    std::cin >> t1 >> t2 >> t3;
    // Get the callback
    callback_t func = getCallbackBasedOnTasks(t1, t2, t3);
    // Invoke the callback
    func();






    share|improve this answer















    Ensuring that if statements are evaluated at compile time



    C++17 introduces if constexpr, which does exactly this:



    template<bool task_1, bool task_2, bool task_3>
    void callback_function()
    if constexpr (task_1)
    std::cout << "Running task 1" << std::endl;

    if constexpr (task_2)
    std::cout << "Running task 2" << std::endl;

    if constexpr (task_3)
    std::cout << "Running task 3" << std::endl;




    If you have optimizations enabled, if constexpr isn't necessary. Even if you use a regular if instead of if constexpr, because the bools are now templated, the compiler will be able to eliminate the if statements entirely, and just run the tasks. If you look at the assembly produced here, you'll see that even at -O1, there are no if statements in any of the callback functions.



    We can now use callback_function directly as a function pointer, avoiding function<void()>:



    int main() 
    using callback_t = void(*)();
    callback_t func = callback_function<true, false, true>;

    // Do stuff with func



    We can also name the bools by assigning them to constexpr variables:



    int main() 
    using callback_t = void(*)();
    constexpr bool do_task1 = true;
    constexpr bool do_task2 = false;
    constexpr bool do_task3 = true;
    callback_t func = callback_function<do_task1, do_task2, do_task3>;

    // Do stuff with func



    Automatically creating a lookup table of all possible callback functions



    You mentioned choosing between different callback functions at runtime. We can do this pretty easily with a lookup table, and we can use templates to automatically create a lookup table of all possible callback functions.



    The first step is to get a callback function from a particular index:



    // void(*)() is ugly to type, so I alias it
    using callback_t = void(*)();

    // Unpacks the bits
    template<size_t index>
    constexpr auto getCallbackFromIndex() -> callback_t

    constexpr bool do_task1 = (index & 4) != 0;
    constexpr bool do_task2 = (index & 2) != 0;
    constexpr bool do_task3 = (index & 1) != 0;
    return callback_function<do_task1, do_task2, do_task3>;



    Once we can do that, we can write a function to create a lookup table from a bunch of indexes. Our lookup table will just be a std::array.



    // Create a std::array based on a list of flags
    // See https://en.cppreference.com/w/cpp/utility/integer_sequence
    // For more information
    template<size_t... Indexes>
    constexpr auto getVersionLookup(std::index_sequence<Indexes...>)
    -> std::array<callback_t, sizeof...(Indexes)>

    return getCallbackFromIndex<Indexes>()...;


    // Makes a lookup table containing all 8 possible callback functions
    constexpr auto callbackLookupTable =
    getVersionLookup(std::make_index_sequence<8>());


    Here, callbackLookupTable contains all 8 possible callback functions, where callbackLookupTable[i] expands the bits of i to get the callback. For example, if i == 6, then i's bits are 110 in binary, so



    callbackLookupTable[6] is callback_function<true, true, false>



    Using the lookup table at runtime



    Using the lookup table is really simple. We can get an index from a bunch of bools by bitshifting:



    callback_t getCallbackBasedOnTasks(bool task1, bool task2, bool task3) 
    // Get the index based on bit shifting
    int index = ((int)task1 << 2) + ((int)task2 << 1) + ((int)task3);
    // return the correct callback
    return callbackLookupTable[index];



    Example demonstrating how to read in tasks



    We can get the bools at runtime now, and just call getCallbackBasedOnTasks to get the correct callback



    int main() 
    bool t1, t2, t3;
    // Read in bools
    std::cin >> t1 >> t2 >> t3;
    // Get the callback
    callback_t func = getCallbackBasedOnTasks(t1, t2, t3);
    // Invoke the callback
    func();







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited yesterday

























    answered yesterday









    Jorge PerezJorge Perez

    1,233416




    1,233416












    • The constexpr is IMHO a red herring, the important part is the use of template parameters which are evaluated at compile time. Any halfway-decent compiler is able to figure this out even without these consexpr hints.

      – Ulrich Eckhardt
      yesterday












    • I updated the answer explaining how to automatically generate a list of all possible callback functions. You can find the right one just by packing the bools into the bits of the index

      – Jorge Perez
      yesterday












    • The lookup table is a runtime solution. You can get the right function just by indexing into it

      – Jorge Perez
      yesterday











    • I added code showing exactly how to do that

      – Jorge Perez
      yesterday






    • 1





      (@$#*!) – can't find anything to criticise any more... Just kidding. But the automatically created lookup table is great, far better than my originally proposed switch statement...

      – Aconcagua
      yesterday


















    • The constexpr is IMHO a red herring, the important part is the use of template parameters which are evaluated at compile time. Any halfway-decent compiler is able to figure this out even without these consexpr hints.

      – Ulrich Eckhardt
      yesterday












    • I updated the answer explaining how to automatically generate a list of all possible callback functions. You can find the right one just by packing the bools into the bits of the index

      – Jorge Perez
      yesterday












    • The lookup table is a runtime solution. You can get the right function just by indexing into it

      – Jorge Perez
      yesterday











    • I added code showing exactly how to do that

      – Jorge Perez
      yesterday






    • 1





      (@$#*!) – can't find anything to criticise any more... Just kidding. But the automatically created lookup table is great, far better than my originally proposed switch statement...

      – Aconcagua
      yesterday

















    The constexpr is IMHO a red herring, the important part is the use of template parameters which are evaluated at compile time. Any halfway-decent compiler is able to figure this out even without these consexpr hints.

    – Ulrich Eckhardt
    yesterday






    The constexpr is IMHO a red herring, the important part is the use of template parameters which are evaluated at compile time. Any halfway-decent compiler is able to figure this out even without these consexpr hints.

    – Ulrich Eckhardt
    yesterday














    I updated the answer explaining how to automatically generate a list of all possible callback functions. You can find the right one just by packing the bools into the bits of the index

    – Jorge Perez
    yesterday






    I updated the answer explaining how to automatically generate a list of all possible callback functions. You can find the right one just by packing the bools into the bits of the index

    – Jorge Perez
    yesterday














    The lookup table is a runtime solution. You can get the right function just by indexing into it

    – Jorge Perez
    yesterday





    The lookup table is a runtime solution. You can get the right function just by indexing into it

    – Jorge Perez
    yesterday













    I added code showing exactly how to do that

    – Jorge Perez
    yesterday





    I added code showing exactly how to do that

    – Jorge Perez
    yesterday




    1




    1





    (@$#*!) – can't find anything to criticise any more... Just kidding. But the automatically created lookup table is great, far better than my originally proposed switch statement...

    – Aconcagua
    yesterday






    (@$#*!) – can't find anything to criticise any more... Just kidding. But the automatically created lookup table is great, far better than my originally proposed switch statement...

    – Aconcagua
    yesterday














    1














    Leave the code as it is.



    Execution time of an "if" compared to writing to std::out is practically zero, so you are arguing over nothing. Well, unless you spend some time measuring the execution time as it is, and with the if's removed according to the values of the three constants, and found that there is a real difference.



    At most, you might make the function inline or static, and the compiler will probably realise the arguments are always the same when optimisation is turned on. (My compiler would give a warning that you are using a function without a prototype, which means you should have either put a prototype into a header file, telling the compiler to expect calls from other call sites, or you should have made it static, telling the compiler that it knows all the calls and can use static analysis for optimisations).



    And what you think is a constant, might not stay a constant forever. The original code will work. Any new code most likely won't.






    share|improve this answer



























      1














      Leave the code as it is.



      Execution time of an "if" compared to writing to std::out is practically zero, so you are arguing over nothing. Well, unless you spend some time measuring the execution time as it is, and with the if's removed according to the values of the three constants, and found that there is a real difference.



      At most, you might make the function inline or static, and the compiler will probably realise the arguments are always the same when optimisation is turned on. (My compiler would give a warning that you are using a function without a prototype, which means you should have either put a prototype into a header file, telling the compiler to expect calls from other call sites, or you should have made it static, telling the compiler that it knows all the calls and can use static analysis for optimisations).



      And what you think is a constant, might not stay a constant forever. The original code will work. Any new code most likely won't.






      share|improve this answer

























        1












        1








        1







        Leave the code as it is.



        Execution time of an "if" compared to writing to std::out is practically zero, so you are arguing over nothing. Well, unless you spend some time measuring the execution time as it is, and with the if's removed according to the values of the three constants, and found that there is a real difference.



        At most, you might make the function inline or static, and the compiler will probably realise the arguments are always the same when optimisation is turned on. (My compiler would give a warning that you are using a function without a prototype, which means you should have either put a prototype into a header file, telling the compiler to expect calls from other call sites, or you should have made it static, telling the compiler that it knows all the calls and can use static analysis for optimisations).



        And what you think is a constant, might not stay a constant forever. The original code will work. Any new code most likely won't.






        share|improve this answer













        Leave the code as it is.



        Execution time of an "if" compared to writing to std::out is practically zero, so you are arguing over nothing. Well, unless you spend some time measuring the execution time as it is, and with the if's removed according to the values of the three constants, and found that there is a real difference.



        At most, you might make the function inline or static, and the compiler will probably realise the arguments are always the same when optimisation is turned on. (My compiler would give a warning that you are using a function without a prototype, which means you should have either put a prototype into a header file, telling the compiler to expect calls from other call sites, or you should have made it static, telling the compiler that it knows all the calls and can use static analysis for optimisations).



        And what you think is a constant, might not stay a constant forever. The original code will work. Any new code most likely won't.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        gnasher729gnasher729

        42.1k44878




        42.1k44878





















            0














            Short of JIT compilation, you can’t do better than your 2^n functions (and the resulting binary size). You can of course use a template to avoid writing them all out. To prevent the source from scaling exponentially just from selecting the correct implementation, you can write a recursive dispatcher (demo):



            template<bool... BB>
            auto g() return f<BB...>;
            template<bool... BB,class... TT>
            auto g(bool b,TT... tt)
            return b ? g<BB...,true>(tt...) : g<BB...,false>(tt...);





            share|improve this answer

























            • If you know something at compiletime, it's easy to template it. Especially in the OP's case.

              – Jorge Perez
              yesterday











            • @JorgePerez: I did say that you could use a template. I do realize now that you can put some of the ifs inside intermediate templates; I’ll edit that in.

              – Davis Herring
              yesterday















            0














            Short of JIT compilation, you can’t do better than your 2^n functions (and the resulting binary size). You can of course use a template to avoid writing them all out. To prevent the source from scaling exponentially just from selecting the correct implementation, you can write a recursive dispatcher (demo):



            template<bool... BB>
            auto g() return f<BB...>;
            template<bool... BB,class... TT>
            auto g(bool b,TT... tt)
            return b ? g<BB...,true>(tt...) : g<BB...,false>(tt...);





            share|improve this answer

























            • If you know something at compiletime, it's easy to template it. Especially in the OP's case.

              – Jorge Perez
              yesterday











            • @JorgePerez: I did say that you could use a template. I do realize now that you can put some of the ifs inside intermediate templates; I’ll edit that in.

              – Davis Herring
              yesterday













            0












            0








            0







            Short of JIT compilation, you can’t do better than your 2^n functions (and the resulting binary size). You can of course use a template to avoid writing them all out. To prevent the source from scaling exponentially just from selecting the correct implementation, you can write a recursive dispatcher (demo):



            template<bool... BB>
            auto g() return f<BB...>;
            template<bool... BB,class... TT>
            auto g(bool b,TT... tt)
            return b ? g<BB...,true>(tt...) : g<BB...,false>(tt...);





            share|improve this answer















            Short of JIT compilation, you can’t do better than your 2^n functions (and the resulting binary size). You can of course use a template to avoid writing them all out. To prevent the source from scaling exponentially just from selecting the correct implementation, you can write a recursive dispatcher (demo):



            template<bool... BB>
            auto g() return f<BB...>;
            template<bool... BB,class... TT>
            auto g(bool b,TT... tt)
            return b ? g<BB...,true>(tt...) : g<BB...,false>(tt...);






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 54 mins ago

























            answered yesterday









            Davis HerringDavis Herring

            8,9121736




            8,9121736












            • If you know something at compiletime, it's easy to template it. Especially in the OP's case.

              – Jorge Perez
              yesterday











            • @JorgePerez: I did say that you could use a template. I do realize now that you can put some of the ifs inside intermediate templates; I’ll edit that in.

              – Davis Herring
              yesterday

















            • If you know something at compiletime, it's easy to template it. Especially in the OP's case.

              – Jorge Perez
              yesterday











            • @JorgePerez: I did say that you could use a template. I do realize now that you can put some of the ifs inside intermediate templates; I’ll edit that in.

              – Davis Herring
              yesterday
















            If you know something at compiletime, it's easy to template it. Especially in the OP's case.

            – Jorge Perez
            yesterday





            If you know something at compiletime, it's easy to template it. Especially in the OP's case.

            – Jorge Perez
            yesterday













            @JorgePerez: I did say that you could use a template. I do realize now that you can put some of the ifs inside intermediate templates; I’ll edit that in.

            – Davis Herring
            yesterday





            @JorgePerez: I did say that you could use a template. I do realize now that you can put some of the ifs inside intermediate templates; I’ll edit that in.

            – Davis Herring
            yesterday










            Alireza Shafaei is a new contributor. Be nice, and check out our Code of Conduct.









            draft saved

            draft discarded


















            Alireza Shafaei is a new contributor. Be nice, and check out our Code of Conduct.












            Alireza Shafaei is a new contributor. Be nice, and check out our Code of Conduct.











            Alireza Shafaei is a new contributor. Be nice, and check out our Code of Conduct.














            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55438306%2fhow-to-avoid-run-time-checks-for-running-parts-of-code-that-become-unreachable-a%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Club Baloncesto Breogán Índice Historia | Pavillón | Nome | O Breogán na cultura popular | Xogadores | Adestradores | Presidentes | Palmarés | Historial | Líderes | Notas | Véxase tamén | Menú de navegacióncbbreogan.galCadroGuía oficial da ACB 2009-10, páxina 201Guía oficial ACB 1992, páxina 183. Editorial DB.É de 6.500 espectadores sentados axeitándose á última normativa"Estudiantes Junior, entre as mellores canteiras"o orixinalHemeroteca El Mundo Deportivo, 16 setembro de 1970, páxina 12Historia do BreogánAlfredo Pérez, o último canoneiroHistoria C.B. BreogánHemeroteca de El Mundo DeportivoJimmy Wright, norteamericano do Breogán deixará Lugo por ameazas de morteResultados de Breogán en 1986-87Resultados de Breogán en 1990-91Ficha de Velimir Perasović en acb.comResultados de Breogán en 1994-95Breogán arrasa al Barça. "El Mundo Deportivo", 27 de setembro de 1999, páxina 58CB Breogán - FC BarcelonaA FEB invita a participar nunha nova Liga EuropeaCharlie Bell na prensa estatalMáximos anotadores 2005Tempada 2005-06 : Tódolos Xogadores da Xornada""Non quero pensar nunha man negra, mais pregúntome que está a pasar""o orixinalRaúl López, orgulloso dos xogadores, presume da boa saúde económica do BreogánJulio González confirma que cesa como presidente del BreogánHomenaxe a Lisardo GómezA tempada do rexurdimento celesteEntrevista a Lisardo GómezEl COB dinamita el Pazo para forzar el quinto (69-73)Cafés Candelas, patrocinador del CB Breogán"Suso Lázare, novo presidente do Breogán"o orixinalCafés Candelas Breogán firma el mayor triunfo de la historiaEl Breogán realizará 17 homenajes por su cincuenta aniversario"O Breogán honra ao seu fundador e primeiro presidente"o orixinalMiguel Giao recibiu a homenaxe do PazoHomenaxe aos primeiros gladiadores celestesO home que nos amosa como ver o Breo co corazónTita Franco será homenaxeada polos #50anosdeBreoJulio Vila recibirá unha homenaxe in memoriam polos #50anosdeBreo"O Breogán homenaxeará aos seus aboados máis veteráns"Pechada ovación a «Capi» Sanmartín e Ricardo «Corazón de González»Homenaxe por décadas de informaciónPaco García volve ao Pazo con motivo do 50 aniversario"Resultados y clasificaciones""O Cafés Candelas Breogán, campión da Copa Princesa""O Cafés Candelas Breogán, equipo ACB"C.B. Breogán"Proxecto social"o orixinal"Centros asociados"o orixinalFicha en imdb.comMario Camus trata la recuperación del amor en 'La vieja música', su última película"Páxina web oficial""Club Baloncesto Breogán""C. B. Breogán S.A.D."eehttp://www.fegaba.com

            Vilaño, A Laracha Índice Patrimonio | Lugares e parroquias | Véxase tamén | Menú de navegación43°14′52″N 8°36′03″O / 43.24775, -8.60070

            Cegueira Índice Epidemioloxía | Deficiencia visual | Tipos de cegueira | Principais causas de cegueira | Tratamento | Técnicas de adaptación e axudas | Vida dos cegos | Primeiros auxilios | Crenzas respecto das persoas cegas | Crenzas das persoas cegas | O neno deficiente visual | Aspectos psicolóxicos da cegueira | Notas | Véxase tamén | Menú de navegación54.054.154.436928256blindnessDicionario da Real Academia GalegaPortal das Palabras"International Standards: Visual Standards — Aspects and Ranges of Vision Loss with Emphasis on Population Surveys.""Visual impairment and blindness""Presentan un plan para previr a cegueira"o orixinalACCDV Associació Catalana de Cecs i Disminuïts Visuals - PMFTrachoma"Effect of gene therapy on visual function in Leber's congenital amaurosis"1844137110.1056/NEJMoa0802268Cans guía - os mellores amigos dos cegosArquivadoEscola de cans guía para cegos en Mortágua, PortugalArquivado"Tecnología para ciegos y deficientes visuales. Recopilación de recursos gratuitos en la Red""Colorino""‘COL.diesis’, escuchar los sonidos del color""COL.diesis: Transforming Colour into Melody and Implementing the Result in a Colour Sensor Device"o orixinal"Sistema de desarrollo de sinestesia color-sonido para invidentes utilizando un protocolo de audio""Enseñanza táctil - geometría y color. Juegos didácticos para niños ciegos y videntes""Sistema Constanz"L'ocupació laboral dels cecs a l'Estat espanyol està pràcticament equiparada a la de les persones amb visió, entrevista amb Pedro ZuritaONCE (Organización Nacional de Cegos de España)Prevención da cegueiraDescrición de deficiencias visuais (Disc@pnet)Braillín, un boneco atractivo para calquera neno, con ou sen discapacidade, que permite familiarizarse co sistema de escritura e lectura brailleAxudas Técnicas36838ID00897494007150-90057129528256DOID:1432HP:0000618D001766C10.597.751.941.162C97109C0155020