如果constexpr(condition)作为编译时条件 [英] if constexpr(condition) as compile-time conditional

查看:130
本文介绍了如果constexpr(condition)作为编译时条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用constexpr bool(在下面的示例中为useF)来启用以下代码中的功能.在这里,调用A::f().另外,在关闭功能的情况下,我希望成为别名模板(a)为void.

I want to use a constexpr bool (useF in the example below) to enable a feature in the following code. Here, calling A::f(). Additionally, I want to be the alias-template (a) to be void in the case I switch off the feature.

我试图使用constexpr if语句,但是主体仍在实例化,这会导致编译错误.如果我使用包装器模板(X),则将按我的预期丢弃该主体,但是对我来说,这似乎很丑陋.还有其他方法吗?

I tried to use a constexpr if statement, but the body is still being instantiated, which causes a compile error. If I use a wrapper template (X), the body is being discarded as I'd expected, but that seems ugly to me. Are there any other ways to do this?

constexpr bool useF = false;

struct A {
    static void f() {}
};

using a = std::conditional<useF, A, void>::type;

template<typename L>
struct X {
    static void h() {
        if constexpr(std::is_same<L, A>::value) {
            L::f(); // not instantiated, no error
        }
    }
};

int main() {
    if constexpr(useF) {
        a::f(); // error!?
    }

    X<a>::h();
}

我正在将g ++-7.0.1与-std = c ++ 17一起使用

I am using g++-7.0.1 with -std=c++17

推荐答案

if constexpr仅适用于模板.来自[stmt.if]:

if constexpr is only for templates. From [stmt.if]:

如果if语句的格式为if constexpr,则条件的值应为上下文转换的类型为bool(5.20)的常量表达式;这种形式称为 constexpr if 语句.如果值 转换后的条件是false,则第一个子语句是废弃的语句,否则,第二个子语句(如果存在)是废弃的语句. 在实例化包含模板的实体期间 (第14条),如果条件在实例化后不依赖于值,则不实例化丢弃的子语句(如果有).

If the if statement is of the form if constexpr, the value of the condition shall be a contextually converted constant expression of type bool (5.20); this form is called a constexpr if statement. If the value of the converted condition is false, the first substatement is a discarded statement, otherwise the second substatement, if present, is a discarded statement. During the instantation of an enclosing templated entity (Clause 14), if the condition is not value-dependent after its instantiation, the discarded substatement (if any) is not instantiated.

X内,constexpr if语句将防止实例化否则格式不正确的语句.这是该语言功能的目标.但是在模板之外,没有这样的等效增益.

Within X, the constexpr if statement will prevent the otherwise ill-formed statement from being instantiated. That is the goal of this language feature. But outside of templates, there's no such equivalent gain.

这篇关于如果constexpr(condition)作为编译时条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆