简体   繁体   中英

Ways to get rid of “conditional expression is constant” warning when checking bool template parameter?

This code template produces the "conditional expression is constant" warning when compiled with /W4 (MSVC 2013):

#include <iostream>

template <bool condition>
struct Conditional
{
    static void f()
    {
        if (condition)
            std::cout << "true";
        else
            std::cout << "false";
    }
};

void main()
{
    Conditional<false>::f();
}

Now, assume Conditional is actually a useful class with lots of methods and lots of code around the condition. I want to get rid of the warning with as little code modification as possible.

The only one trick I know is tag dispatching. It's acceptable, but a bit clumsy since I need to declare 2 additional methods and extract the condition code there. Are there any other ways?

You may use specialization:

template <bool condition>
struct Conditional
{
    static void f();
};

template <>
void Conditional<true>::f() { std::cout << "true"; }

template <>
void Conditional<false>::f() { std::cout << "false"; }

Live example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM