I want to write a template function that works only with two numbers (for example, 3 and 5), and gives errors if you try to use it with other numbers.
I can do it like this:
template<int x> void f(); template<> void f<3>() { cout << "f<3>()\n"; } template<> void f<5>() { cout << "f<5>()\n"; }
and then I can call this function in the usual way:
f<3>(); f<5>();
and it compiles well, and if I try to misuse my function:
f<10>();
the compiler gives me an error.
I have 2 problems with this approach:
1.- Is this standard? Is it possible to specialize a template using ints?
2.- I do not like the error you get if you use this approach, because the error does not tell the user what he did wrong. I would rather write something like:
template<int x> void f() { static_assert(false, "You are trying to use f with the wrong numbers"); }
but it does not compile. It looks like my compiler (gcc 5.4.0) is trying to create the first primary template, and because of this it gives an error (static_assert).
Thank you for your help.
If you are wondering why I want to do this, this is because I am learning how to program a microcontroller. In the microcontroller, you have several contacts that only do some things. For example, pins 3 and 5 are pins in which you can create a square wave. If in the application I want to create a square wave, I want to write somthing like:
square_wave<3>(frecuency);
But if a few months later I want to reuse this code (or change it) in another application using another microcontroller, I want my compiler to tell me: "In this microcontroller, you cannot create a square wave in pins 3 and 5. Instead use contacts 7 and 9 ". And I think this can save me a lot of headaches (or maybe not, I really don't know. I'm just learning how to program a microcontroller).