wim*_*aan 4 c++ c++17 if-constexpr
我想使用constexpr bool(useF在下面的示例中)来启用以下代码中的功能.在这里,打电话A::f().另外,我希望在关闭该功能的情况下成为alias-template(a)void.
我试图使用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();
}
Run Code Online (Sandbox Code Playgroud)
我正在使用g ++ - 7.0.1和-std = c ++ 17
if constexpr仅适用于模板.来自[stmt.if]:
如果
if语句是表单if constexpr,则条件的值应为类型bool(5.20)的上下文转换常量表达式; 此表单称为constexpr if语句.如果转换条件的值是false,则第一个子语句是废弃语句,否则第二个子语句(如果存在)是废弃语句.在封闭的模板化实体(第14条)的瞬间期间,如果条件在其实例化之后不依赖于值,则不实例化丢弃的子语句(如果有的话).
在其中X,constexpr if语句将阻止实例化其他格式错误的语句.这是此语言功能的目标.但是在模板之外,没有这样的等效收益.
| 归档时间: |
|
| 查看次数: |
1173 次 |
| 最近记录: |