gpt4 book ai didi

c++ - 对 std::array 的模板化引用未在 MSVC 中调用 SFINAE*。漏洞?

转载 作者:行者123 更新时间:2023-12-04 07:50:11 25 4
gpt4 key购买 nike

我遇到了将模板化数组引用升级到 std::array 的问题我在哪里使用过这个:

template<class T, int N>
void f(T(&a)[N]){/* do stuff */;}
这在我使用过的所有编译器中都有效,所以我只是在更改为 std::array 时这样做了。
template<class T, int N>
void f(std::array<T,N>& a){/* do stuff */;}
这在 MSVC 上运行良好。但是当我在其他编译器上运行代码时,它没有
以下代码适用于 MSVC,但不适用于其他编译器。见 https://godbolt.org/z/d9cqWMeaM匹配失败,因为 N 必须是 std::size_t .
*这个 question表示应申请 SFINAE。然而,正如评论中所指出的,尽管有这个答案,SFINAE 通常适用于拒绝格式错误的声明。这是演绎失败。
MSVC 接受此代码是编译器错误吗?并且是 T(&a)[N]哪里 int N即使我使用过的所有编译器都没有问题,但使用合法吗?
这有点烦人,因为一些先前的代码使用了 N 在不同地方签名的事实。

最佳答案

std::array size_typespecifiedstd::size_t .
GCC 和 Clang 是对的,根据 [temp.deduct.type]/18,在这种情况下模板推导应该失败。 :

If P has a form that contains <i>, and if the type of i differs from the type of the corresponding template parameter of the template named by the enclosing simple-template-id, deduction fails.
. . .

[ Example:

template<int i> class A { /* ... */ };
template<short s> void f(A<s>);
void k1() {
A<1> a;
f(a); // error: deduction fails for conversion from int to short
f<1>(a); // OK
}

注意:在 C++11 中,这条规则更易读,见 here .
所以从技术上讲,MSVC 对代码的接受是一个错误。我会将其报告给供应商(帮助 -> 发送反馈 -> 报告问题)。

关于c++ - 对 std::array 的模板化引用未在 MSVC 中调用 SFINAE*。漏洞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67027971/

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