【发布时间】:2021-01-09 20:53:47
【问题描述】:
使用最新版本的 Visual Studio 2019 和 Visual Studio。在这两个中,我都试图使用这个仅标题的类来显示一个向量:
#pragma once
#include <cstring>
#include <iterator>
#include <vector>
// Header-only helper class for using strings
class stringHelper
{
public:
// Constructor / destructor
stringHelper() {}
~stringHelper() {}
template <class T>
void PrintVector(std::vector<T> input, const char cSeparator = ' ', bool bNewLine = false)
{
// Output an array (std::vector) to the console eg. {1,11,21} => 1 11 21.
// Example usage: stringHelper::PrintVector<int>(vecOfInts);
if (input.size() > 0)
{
for (std::vector<T>::iterator it = input.begin(); it != input.end();)
{
std::cout << *it;
if (++it != input.end())
std::cout << cSeparator;
}
if (bNewLine)
std::cout << std::endl;
}
}
};
Visual Studio Code 已配置为使用 Visual Studio 2019 中的 cl.exe 编译器,如下所示:
{
// Use MSVC cl.exe (eg. Visual Studio 2019) on Windows
"type": "shell",
"label": "cl.exe: Build active file (DEBUG)",
"command": "cl.exe",
"args": [
"/std:c++17",
"/Zi",
"/EHsc",
"/Fe:",
"${fileDirname}\\${fileBasenameNoExtension}.exe",
"${file}"
],
"options": {
"cwd": "${workspaceFolder}"
},
"problemMatcher": [
"$msCompile"
],
"group": {
"kind": "build",
"isDefault": true
}
}
一个简单的测试程序可能是:
#include <vector>
#include "stringHelper.h"
int main()
{
// Create and print out a vector
stringHelper helper;
std::vector<int> vec = {1, 2, 17};
helper.PrintVector<int>(vec); // Expecting: 1 2 17
return 0;
}
在 Visual Studio Code 中,程序编译并产生正确的结果。 Visual Studio 项目配置为使用 C++17(我也尝试过 C++14)。我在 Visual Studio 2019 Professional 中编译时,生成多个C2760 编译错误:
Error C2760 syntax error: unexpected token 'identifier', expected ';'
当我在Error List 中选择这一行时,标记it 会突出显示。
将PrintVector 中的内部循环更改为以下内容,这与我所需要的略有不同。现在一切都在 Visual Studio Code 和 2019 中编译并运行良好:
for (auto a : input)
{
std::cout << a << cSeparator;
}
Microsoft help on C2760 似乎不适用。这是编译器还是 VS 2019 错误?为什么这在 Visual Studio 2019 中失败了,而在 Visual Studio Code 中却没有?
【问题讨论】:
-
确实,代码不正确,所以bug其实是它编译的。
-
@Den-Jason:行得通!在
for循环中将std::vector<T>::iterator it更改为auto it允许它编译和工作。为什么?这感觉像是 VS2019 的错误。 -
已将此作为(可能的)编译器错误直接从
Visual Studio > Help > Send Feedback > Report a Problem...提交给 Microsoft,如果我得到回复,将更新问题。 -
啊,很好的发现,谢谢。我将不得不尝试使用该链接中提到的
typename技巧。在这里使用auto感觉像是在逃避,因为我希望编译器能够处理命名迭代器。
标签: c++ visual-studio-code visual-studio-2019