False-branch of if constexpr not discarded in templated lambda

女生的网名这么多〃 提交于 2019-12-05 01:18:15

According to the code linked,

template<bool condition>
void print_fun(foo_bar & obj) {
    std::cout << obj.x << std::endl;
    if constexpr(condition)
        std::cout << obj.y << std::endl;
}

The problem is with if constexpr being used, the statement std::cout << obj.y << std::endl; is ill-formed for every possible instantiation of the template print_fun; i.e. no matter what's the value of condition it's just always ill-formed.

Note: the discarded statement can't be ill-formed for every possible specialization:

The common workaround for such a catch-all statement is a type-dependent expression that is always false:

To fix it you can make the statement to dependent on the template parameter, e.g.

template <bool condition>
using foo_bar = Combined<condition, foo, bar>;

template<bool condition>
void print_fun(foo_bar<condition> & obj) {
    std::cout << obj.x << std::endl;
    if constexpr(condition)
        std::cout << obj.y << std::endl;
}

and use it as

foo_bar<no> obj = {};
print_fun<no>(obj);

Now for obj.y, obj is of type foo_bar<condition>, which depends on the template parameter condition.

LIVE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!