Search code examples
c++templatesstatic-if

Is there a C++ programming technique which is an approximate equivalent of a runtime #ifdef?


For example I have a function call in some code I want to be able to enable/disable as I like.

Normally I could just use an if, but then it would check each time if the function can be ran, which I don't want. I simply want the code to never do that check.

ifdef blocks can be messy and quite dirty, they pile up and make code hard to read.

Can't I solve this with some sort of template ? I know I can make multiple lambdas to build each version of the possible function call I'd want.

Is this what a static if means ? Because in my mind, what I want to do is a self modifying code, which I don't know if it's a good idea or possible at all.


Solution

  • If I have not misunderstood your question, I think you want something like the Strategy design pattern which is for runtime decision.

    But just because you asked for a template, here is an example using Policy based template metaprogramming... But here, the decision is taken at compile time.

    struct task {
        void do_task() { /* really do the task... */ }
    };
    
    struct no_task {
        void do_task() {} // empty
    };
    
    template<typename Task> class host : public Task {};
    
    // here you take the decision...
    // you can pass either task or no_task
    host<task> h;
    
    // and later you call the function...
    h.do_task();
    

    Using templates is really efficient.
    There is no indirection through any pointer to function.
    It is easy for compilers to inline the function.
    If you pass it no_task, the call site won't even have a call to the empty function(check that out with your compiler's optimization levels).