Tell me how to include / exclude code in the template <int options> template depending on the value of options. I do not want to write extra templates due to small differences.

    2 answers 2

    It is difficult to say something more specific, since very little information was given. I can, as a possible option, offer a part of the variable code to enclose it in another template function or class and already specialize it. for example

    #include <iostream> template <int option> void func(); template<> void func<1> () { std::cout << "RES 1\n"; } template<> void func<2> () { std::cout << "RES 21\n"; } template <int option> void func_gen () { func<option> (); } int main() { func_gen<1>(); func_gen<2>(); } 
    • If I understand correctly, @mikelsv wants the code snippet not to compile at all. And specialized templates, like regular functions, will be compiled. In general, +1 is a good option. - IronVbif
    • It turned out like hell, but it looks like it happened. AddToList <options & OLIST_OPT_LIST> (el); In principle, it is possible to scatter all options. ) Great. - mikelsv

    A normal if statement will do. Example:

     template <int options> int getNumber() { if (options == 5) return 6; if (options == 7) return 2; return 8; } int main() { int a = getNumber<5>(); int b = getNumber<7>(); int c = getNumber<67>(); int d = getNumber<6456>(); } 

    4 functions will be created (-O0 key):

     int getNumber<5>(): # @int getNumber<5>() movl $6, %eax ret int getNumber<7>(): # @int getNumber<7>() movl $2, %eax ret int getNumber<67>(): # @int getNumber<67>() movl $8, %eax ret int getNumber<6456>(): # @int getNumber<6456>() movl $8, %eax ret 

    Try to skip your function through http://gcc.godbolt.org/ and see what remains in it with different parameters.

    • Does not work. if (options & OLIST_OPT_LIST) {use.OMAdd (el); } The code must be specifically excluded, so that the compiler does not use it. - mikelsv
    • Show a bit more code to guess what you are writing there. - KoVadim
    • What's the point? The whole problem is <code> template <int options> class A {A () {if (options) {anyname_class zzz; }}}; </ code> - mikelsv
    • What does it mean to exclude? if it will exclude it and it will not be called (But it will still be compiled). Do you want #ifdef for compile time constants in a template? There is no such thing. - IronVbif
    • @mikelsv: Well, look. You write as if the condition checked in runtime ( if (options ...) ). But since the value of the constant is known in compile time, the check will be performed at the compilation stage - just what you need. - VladD