gpt4 book ai didi

c++ - 'if constexpr branch' 不会在模板函数内的 lambda 内被丢弃

转载 作者:IT老高 更新时间:2023-10-28 12:51:45 24 4
gpt4 key购买 nike

以下code :

#include <type_traits>

struct X {
static constexpr void x() {}
};

template <class T1, class T2>
constexpr bool makeFalse() { return false; }

template <class T>
void foo() {
T tmp;
auto f = [](auto type) {
if constexpr (makeFalse<T, decltype(type)>()) {
T::x(); // <- clang does not discard
} else {
// noop
}
};
}

int main() {
foo<int>();
}

不使用 Clang 编译,但使用 GCC 编译。我看不出这段代码有什么问题,但我不确定。 Clang 是不是没有编译它?

最佳答案

[stmt.if]/2 :

During the instantiation of an enclosing templated entity, if the condition is not value-dependent after its instantiation, the discarded substatement (if any) is not instantiated.

自从 makeFalse<T, decltype(type)>()foo<int> 的实例化之后 依赖于值,看来 T::x()应该按照标准实例化,并且因为 T::x T 时格式不正确是 int , Clang 不编译是对的。

关于c++ - 'if constexpr branch' 不会在模板函数内的 lambda 内被丢弃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55909018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com