考虑以下在 Clang 3.8 上成功编译的问题:-std=c++14
.
#include <boost/hana.hpp>
namespace hana = boost::hana;
int main() {
constexpr auto indices = hana::range<unsigned, 0, 3>();
hana::for_each(indices, [&](auto i) {
hana::for_each(indices, [&](auto j) {
constexpr bool test = (i == (j == i ? j : i));
static_assert(test, "error");
});
});
}
这个测试完全没有意义,但这不是重点。现在考虑一个替代版本,其中测试直接放入static_assert
:
#include <boost/hana.hpp>
namespace hana = boost::hana;
int main() {
constexpr auto indices = hana::range<unsigned, 0, 3>();
hana::for_each(indices, [&](auto i) {
hana::for_each(indices, [&](auto j) {
static_assert((i == (j == i ? j : i)), "error");
});
});
}
现在我收到一堆编译错误,说
错误:引用局部变量i
在封闭的 lambda 表达式中声明
问题:什么原因导致第二个版本失败?
编辑:这可能是编译器错误吗?我发现当访问时i
之前static_assert
,一切再次编译:
#include <boost/hana.hpp>
namespace hana = boost::hana;
int main() {
constexpr auto indices = hana::range<unsigned, 0, 3>();
hana::for_each(indices, [&](auto i) {
hana::for_each(indices, [&](auto j) {
constexpr auto a = i;
static_assert((i == (j == i ? j : i)), "error");
});
});
}
更新:相同的行为可以在 Clang 4.0 和当前开发分支 5.0 上重现。
更新 2:根据@LouisDionne 的建议,我将此作为错误提交:https://bugs.llvm.org/show_bug.cgi?id=33318 https://bugs.llvm.org/show_bug.cgi?id=33318.