简体   繁体   English

如果 constexpr(condition) 作为编译时条件

[英]if constexpr(condition) as compile-time conditional

I want to use a constexpr bool ( useF in the example below) to enable a feature in the following code.我想使用 constexpr bool(下面示例中的useF )来启用以下代码中的功能。 Here, calling A::f() .在这里,调用A::f() Additionally, I want to be the alias-template ( a ) to be void in the case I switch off the feature.此外,我想在我关闭该功能的情况下成为void的别名模板( a )。

I tried to use a constexpr if statement, but the body is still being instantiated, which causes a compile error.我尝试使用 constexpr if 语句,但主体仍在被实例化,这会导致编译错误。 If I use a wrapper template ( X ), the body is being discarded as I'd expected, but that seems ugly to me.如果我使用包装器模板 ( X ),则正文将按我的预期被丢弃,但这对我来说似乎很难看。 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();
}

I am using g++-7.0.1 with -std=c++17我使用 g++-7.0.1 和 -std=c++17

if constexpr is only for templates. if constexpr仅用于模板。 From [stmt.if]:来自 [stmt.if]:

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);如果if语句的形式为if constexpr ,则条件的值应为bool (5.20) 类型的上下文转换常量表达式; this form is called a constexpr if statement.这种形式称为constexpr if语句。 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.如果转换条件的值为false ,则第一个子语句丢弃的语句,否则第二个子语句(如果存在)是丢弃的语句。 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.在封闭模板化实体的实例化期间(第 14 条) ,如果条件在实例化后不依赖于值,则不会实例化丢弃的子语句(如果有)。

Within X , the constexpr if statement will prevent the otherwise ill-formed statement from being instantiated.X , constexpr if 语句将阻止其他格式错误的语句被实例化。 That is the goal of this language feature.这就是此语言功能的目标。 But outside of templates, there's no such equivalent gain.但是在模板之外,没有这样的等效增益。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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