gpt4 book ai didi

c++ - MSVC 中可能的编译器错误

转载 作者:行者123 更新时间:2023-12-04 02:14:09 26 4
gpt4 key购买 nike

以下代码使用 gcc 和 clang(以及许多其他 C++11 编译器)进行编译

#include <stdint.h>

typedef int datatype;

template <typename T>
struct to_datatype {};

template <>
struct to_datatype<int16_t> {
static constexpr datatype value = 1;
};

template <typename T>
class data {
public:
data(datatype dt = to_datatype<T>::value) {}
};

int main() {
data<char> d{to_datatype<int16_t>::value};
}

使用(几乎)最新的 MSVC 编译时
> cl .\test.cpp /std:c++latest /permissive-
Microsoft (R) C/C++ Optimizing Compiler Version 19.24.28314 for x64
Copyright (C) Microsoft Corporation. All rights reserved.

test.cpp
.\test.cpp(16): error C2039: 'value': is not a member of 'to_datatype<T>'
with
[
T=char
]
.\test.cpp(16): note: see declaration of 'to_datatype<T>'
with
[
T=char
]
.\test.cpp(20): note: see reference to class template instantiation 'data<char>' being compiled

这是MSVC的错误吗?如果是,C++ 标准中的哪个术语最能描述它?

如果您将部分代码替换为
template <typename T>
class data {
public:
data(datatype dt) {}
data() : data(to_datatype<T>::value) {}
};

无论如何它编译顺利。

最佳答案

我会说 MSVC 不接受代码是错误的。

根据 [dcl.fct.default]/5在 C++17 标准最终草案中,类模板的成员函数的默认参数中的名称查找是根据 [temp.inst] 中的规则完成的。

根据 [temp.inst]/2类模板的隐式实例化不会导致成员函数的默认参数的实例化,根据 [temp.inst]/4 (非显式特化)类模板的成员函数的默认参数在调用使用时被实例化。

没有使用默认参数的调用 to_datatype<T>::value在你的代码中,所以它不应该被实例化。因此,查找 value 不应该出现错误。在 to_datatype<char>失败。

(C++11 标准最终草案中的相关部分具有等效的措辞,除了编号外,请参见 [decl.fct.default]/5[temp.inst]/1[temp.inst]/3 。)

关于c++ - MSVC 中可能的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59546755/

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