具有两个相同类型的自动参数的 MSVC lambda
MSVC lambda with two auto params of same type
似乎 Visual Studio 的行为与 GCC 和 Clang 不同,给定以下代码:
auto f2 = [](auto x, decltype(x) y)
{
return x + y;
};
f2(1, 2);
Clang 和 GCC 会接受这个,但 MSVC 会抱怨消息
error C3536: 'x': cannot be used before it is initialized
是否有解决方法来强制 2 个参数类型相等?
Nb:此问题可以在 Visual Studio 2015、2017 和 Pre-2018
中重现
参见this code on compiler explorer(您可以在其中切换不同的编译器)
编辑:
这段代码的行为与阅读它时所期望的不同:只要 decltype(y) 可转换为 decltype(x),它就会编译,而不仅仅是当它们相等时。
所以,@n.m。 @max66 的答案是正确的:第一个是如果你想强制类型相等,第二个是如果你想使用 is_convertible。
我接受了第二个,因为它保留了原始代码的行为(尽管原始代码可能是错误的:在我的情况下比较类型相等性更好)
不完全是你问的,但是......也许你可以将它强加在 lambda 中,使用另一个 lambda
auto f2 = [] (auto x, auto y)
{ return [](decltype(x) a, decltype(x) b) {return a + b;}(x, y); };
auto f2 = [](auto x, auto y)
{
static_assert(std::is_same<decltype(x), decltype(y)>::value,
"Argument types must be the same");
return x + y;
};
为了更忠实地模拟原始行为,您可以尝试 is_convertible
而不是 is_same
(但出于某种原因,某些 MSVC 版本 ICE 在它上面)。
似乎 Visual Studio 的行为与 GCC 和 Clang 不同,给定以下代码:
auto f2 = [](auto x, decltype(x) y)
{
return x + y;
};
f2(1, 2);
Clang 和 GCC 会接受这个,但 MSVC 会抱怨消息
error C3536: 'x': cannot be used before it is initialized
是否有解决方法来强制 2 个参数类型相等?
Nb:此问题可以在 Visual Studio 2015、2017 和 Pre-2018
中重现参见this code on compiler explorer(您可以在其中切换不同的编译器)
编辑:
这段代码的行为与阅读它时所期望的不同:只要 decltype(y) 可转换为 decltype(x),它就会编译,而不仅仅是当它们相等时。
所以,@n.m。 @max66 的答案是正确的:第一个是如果你想强制类型相等,第二个是如果你想使用 is_convertible。
我接受了第二个,因为它保留了原始代码的行为(尽管原始代码可能是错误的:在我的情况下比较类型相等性更好)
不完全是你问的,但是......也许你可以将它强加在 lambda 中,使用另一个 lambda
auto f2 = [] (auto x, auto y)
{ return [](decltype(x) a, decltype(x) b) {return a + b;}(x, y); };
auto f2 = [](auto x, auto y)
{
static_assert(std::is_same<decltype(x), decltype(y)>::value,
"Argument types must be the same");
return x + y;
};
为了更忠实地模拟原始行为,您可以尝试 is_convertible
而不是 is_same
(但出于某种原因,某些 MSVC 版本 ICE 在它上面)。