gpt4 book ai didi

c++ - 具有 integer_sequence 的专用模板。海湾合作委员会与 MSVC

转载 作者:行者123 更新时间:2023-12-01 14:47:26 24 4
gpt4 key购买 nike

所以,我遇到了一段在 GCC 和 MSVC 中表现不同的代码:

#include <utility>

typedef int IType;

template<typename> struct A;

template<int... Ns>
struct A<std::integer_sequence<IType, Ns...>> {
using type = bool;
};

using B = typename A<std::make_integer_sequence<IType, 3>>::type;

int main() {
B b;
}
这很高兴在两个编译器上编译。但是,如果您将 IType 定义为 typedef long IType; MSVC 仍然有效,而 GCC 说:
source>:12:61: error: invalid use of incomplete type 'struct A<std::integer_sequence<long int, 0, 1, 2> >'

12 | using B = typename A<std::make_integer_sequence<IType, 3>>::type;

| ^~~~

<source>:5:27: note: declaration of 'struct A<std::integer_sequence<long int, 0, 1, 2> >'

5 | template<typename> struct A;

| ^

<source>: In function 'int main()':

<source>:15:3: error: 'B' was not declared in this scope

15 | B b;

| ^

Compiler returned: 1
因此,显然当 IType 很长时,GCC 无法使用 A 的第二个更专业的定义,因此失败。我真的很难理解为什么 intlong在这里被 GCC 区别对待。
我在编译器资源管理器中使用 GCC 10.1 和 MSVC 19.24 来玩它。
https://godbolt.org/z/7L3xap

最佳答案

std::integer_sequence 被定义为

template< class T, T... Ints >
class integer_sequence;
也就是说,值的类型是 T .
所以当改变 ITypelong ,也是 Ns...的类型应改为 long... :
typedef int IType;

template<typename> struct A;

template<IType... Ns> // <--- HERE
struct A<std::integer_sequence<IType, Ns...>> {
using type = bool;
};
否则,您将获得特化 struct A<long, int, int, int>哪个不匹配 struct A<long, long, long, long> (MSVC 似乎对此更宽容,但 GCC 行为在 IMO 上更正确)。

关于c++ - 具有 integer_sequence 的专用模板。海湾合作委员会与 MSVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62634760/

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