繁体   English   中英

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

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

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

我尝试使用 constexpr if 语句,但主体仍在被实例化,这会导致编译错误。 如果我使用包装器模板 ( X ),则正文将按我的预期被丢弃,但这对我来说似乎很难看。 有没有其他方法可以做到这一点?

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

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

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

X , constexpr if 语句将阻止其他格式错误的语句被实例化。 这就是此语言功能的目标。 但是在模板之外,没有这样的等效增益。

暂无
暂无

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

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