gpt4 book ai didi

c++ - 如果我的模板类型首先作为 lambda 参数出现,MSVC 会引发一个奇怪的错误

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:21:19 26 4
gpt4 key购买 nike

考虑这段代码:

#define SOLUTION 0

template <class T>
constexpr int one = 1;

template <class T>
struct A {
static constexpr int o = one<A<T>>;

void call() {
static_assert(one<A<T>> == 1, "Failure");
}
};

int main() {
#if SOLUTION
A<int> object;
#endif

[](A<int> a) {
a.call();
};

return 0;
}

构建成功here on ideone , 无论 SOLUTION 的值如何定义。

现在,我知道这段代码没有什么实际意义,但那是因为我认真地试图找到这种奇怪行为的最小工作示例。如果我使用最新的 Visual Studio 2017(平台工具集 v141,_MSC_VER = 1910)构建它,我会收到以下错误:

1>source.cpp(11): error C2131: expression did not evaluate to a constant
1>source.cpp(11): note: failure was caused by a read of an uninitialized symbol
1>source.cpp(11): note: see usage of 'one<A<int>>'
1>source.cpp(10): note: while compiling class template member function 'void A<int>::call(void)'
1>source.cpp(21): note: see reference to function template instantiation 'void A<int>::call(void)' being compiled
1>source.cpp(21): note: see reference to class template instantiation 'A<int>' being compiled

有趣的是,当我为 SOLUTION 输入 1 时宏,它构建成功。唯一的区别是未使用的 A<int> object;变量在 main 中定义编译器到达 lambda 定义之前的作用域。

如果在 main 之前,我定义一个这样的函数也很好:

void f(A<int>& a) {
a.call();
}

事实上,它解决问题的效果与变量定义一样好。

是编译器的bug还是上面那段代码违反了标准?

最佳答案

引用 Ajay :

Compiles on VS2017 update 3, but not on (RTM) update 2

我也在我的机器上确认了这种行为。这意味着存在相关的更正并将很快引入生产版本本身,因此我认为这个错误不值得进一步注意。

关于c++ - 如果我的模板类型首先作为 lambda 参数出现,MSVC 会引发一个奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44307588/

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