Gasim
Gasim

Reputation: 7961

How do I "enable" a function based on a template parameter?

I have a a template function:

template<class Route, bool enabled=true>
void addRoute() {
    std::cout << "Route added";
}

I want to disable the function if enabled=false. I know there is no way to disable calling of a function from parameters unless using macros. However, since this function will be called once through the lifetime of the program, I don't mind calling an empty function if enabled is set to false. So, I tried the first thing that came to mind:

template<class Route>
void addRoute<false>() { }

This failed, so I did some digging and found out that partial template specialization is not possible; I can create a partially specialized class with arguments and do the same thing.

Is there another way to do this problem or should I stick with creating a class with static function?

Upvotes: 1

Views: 166

Answers (1)

Daniel Frey
Daniel Frey

Reputation: 56863

How do you want to "disable" the function if you explicitly specify the second parameter? It's true by default and it's not deduced, so the only way to call this function is via

addRoute<RouteType, false>();

In that context, "disabled" could only mean it generates an error, right? If you want that, just add

static_assert( enabled, "Not enabled!" );

to the function's body as the first line. Or if you want to just "skip" the code inside, you can simply add

if( !enabled ) return;

as the first line. The optimizer will make sure that no superfluous code will be generated.

Upvotes: 2

Related Questions