Я делаю функцию для случайного заполнения двумерного массива. У меня есть класс Matrix(темплейтовый). Мне нужно в зависимости от типа данных который там находится поместить значение правильного типа.
Вот мой код:
void randomFill(int min = 0, int max = 10)
{
string typeID;
typeID = (string)(typeid(type).name());
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
if (typeID == "int") data[i][j] = rand() % (int)((max - min + 1) + min);
else if (typeID == "float") data[i][j] = rand() % (float)((max - min + 1) + min);
else if(typeID == "double") data[i][j] = rand() % (double)((max - min + 1) + min);
}
}
}
type — это тип текущего класа.
У меня вылетает следующая ошибка:
Ошибка C2760 синтаксическая ошибка: непредвиденный токен "идентификатор"; требуется ";"
Код целиком:
template <typename type>
class Matrix
{
private:
unsigned int row;
unsigned int col;
type** data;
public:
~Matrix()
{
for (size_t i = 0; i < row; i++)
{
delete[] data[i];
data[i] = nullptr;
}
data = nullptr;
}
Matrix(int row, int col)
{
data = new type * [row];
for (size_t i = 0; i < row; i++)
{
data[i] = new type[col];
}
this->row = row;
this->col = col;
}
Matrix(const Matrix<type>& elem) : Matrix(elem.row, elem.col)
{
for (size_t i = 0; i < row; i++)
{
for (size_t j
= 0; j < col; j++)
{
data[i][j] = elem.data[i][j];
}
}
}
template <typename type>
static void createArr2D(type**& init, int row, int col)
{
init = new type * [row];
for (size_t i = 0; i < row; i++)
{
init[i] = new type[col];
}
}
template <typename type>
static void DeleteArr2D(type**& init, int row)
{
for (size_t i = 0; i < row; i++)
{
delete[] init[i];
init[i] = nullptr;
}
init = nullptr;
}
static int MaxLenElemArr2D(type** init, int row, int col)
{
int res = 0;
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
if (std::to_string(init[i][j]).size() > res) res = std::to_string(init[i][j]).size();
}
}
return res;
}
friend std::ostream& operator<<(std::ostream& out, Matrix<type> p)
{
int maxLen = MaxLenElemArr2D(p.data, p.row, p.col);
for (size_t i = 0; i < p.row; i++)
{
for (size_t j = 0; j < p.col; j++)
{
out << std::setw(maxLen+2) << p.data[i][j];
}
out << std::endl;
}
return out;
}
friend std::istream& operator>>(std::istream& in, Matrix<type>& p)
{
for (size_t i = 0; i < p.row; i++)
{
COORD coord;
coord.Y = i + 1;
for (size_t j = 0; j < p.col; j++)
{
if (j == 0) coord.X = j + 1;
bool flag;
do
{
int tmp;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
in >> tmp;
p.data[i][j] = tmp;
int size_tmpElem = std::to_string(tmp).size();
if (in.fail())
{
in.clear();
in.ignore(32767, 'n');
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
for (size_t i = 0; i < 100; i++) std::cout << " ";
flag = true;
}
else
{
flag = false;
coord.X += size_tmpElem + 2;
}
} while (flag);
}
}
return in;
}
friend Matrix operator+(Matrix<type>& first, Matrix<type>& second)
{
/* if (first.row != second.col || first.row != second.row) return;*/
Matrix<type> tmp(first.row, first.col);
for (size_t i = 0; i < first.row; i++)
{
for (size_t j = 0; j < first.col; j++)
{
tmp.data[i][j] = first.data[i][j] + second.data[i][j];
}
}
return tmp;
}
friend Matrix operator-(Matrix<type>& first, Matrix<type>& second)
{
/* if (first.row != second.col || first.row != second.row) return;*/
Matrix<type> tmp(first.row, first.col);
for (size_t i = 0; i < first.row; i++)
{
for (size_t j = 0; j < first.col; j++)
{
tmp.data[i][j] = first.data[i][j] - second.data[i][j];
}
}
return tmp;
}
friend Matrix operator*(Matrix<type>& first, Matrix<type>& second)
{
/* if (first.row != second.col || first.row != second.row) return;*/
Matrix<type> tmp(first.row, first.col);
for (size_t i = 0; i < tmp.row; i++)
{
for (size_t j = 0; j < tmp.col; j++)
{
tmp.data[i][j] = first.data[i][j] * second.data[i][j];
}
}
return tmp;
}
friend Matrix operator/(Matrix<type>& first, Matrix<type>& second)
{
/* if (first.row != second.col || first.row != second.row) return;*/
Matrix<type> tmp(first.row, first.col);
for (size_t i = 0; i < first.row; i++)
{
for (size_t j = 0; j < first.col; j++)
{
if (second.data[i][j] == 0) tmp.data[i][j] = 0;
else tmp.data[i][j] = first.data[i][j] / second.data[i][j];
}
}
return tmp;
}
/*Matrix& operator=(Matrix<type>& second)
{
if (data != nullptr)
{
clear();
}
row = second.row;
col = second.col;
data = new type * [row];
for (size_t i = 0; i < col; i++)
{
data[i] = new type[col];
}
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
data[i][j] = second.data[i][j];
}
}
return *this;
}*/
Matrix& operator=(Matrix<type> second)
{
if (data != nullptr)
{
clear();
}
row = second.row;
col = second.col;
data = new type * [row];
for (size_t i = 0; i < col; i++)
{
data[i] = new type[col];
}
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
data[i][j] = second.data[i][j];
}
}
return *this;
}
friend bool operator==(Matrix<type>& first, Matrix<type>& second)
{
if (first.row != second.row || first.col != second.col) return false;
for (size_t i = 0; i < first.row; i++)
{
for (size_t j = 0; j < first.col; j++)
{
if (first.data[i][j] != second.data[i][j]) return false;
}
}
return true;
}
friend bool operator!=(Matrix<type>& first, Matrix<type>& second)
{
if (first.row != second.row || first.col != second.col) return true;
for (size_t i = 0; i < first.row; i++)
{
for (size_t j = 0; j < first.col; j++)
{
if (first.data[i][j] != second.data[i][j]) return true;
}
}
return false;
}
void clear()
{
for (size_t i = 0; i < row; i++)
{
delete[] data[i];
data[i] = nullptr;
}
data = nullptr;
row = 0;
col = 0;
}
void randomFill(int min = 0, int max = 10)
{
/*string typeID;
typeID = (string)(typeid(type).name());*/
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
data[i][j] = rand() % (int)((max - min + 1) + min);
/*if (typeID == "int") data[i][j] = rand() % (int)((max - min + 1) + min);
else if (typeID == "float") data[i][j] = rand() % (float)((max - min + 1) + min);
else if(typeID == "double") data[i][j] = rand() % (double)((max - min + 1) + min);*/
}
}
}
void print()
{
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
std::cout << std::setw(3) << data[i][j];
}
std::cout << std::endl;
}
}
void transposition()
{
type** NewData = new type * [col];
// создаем новый массив с реверсивным количеством строк и колонок
for (size_t i = 0; i < col; i++)
{
NewData[i] = new type[row];
}
// Перенос данных
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
NewData[j][i] = data[i][j];
}
}
// Очищаем прошлые данные
for (size_t i = 0; i < row; i++)
{
delete[] data[i];
data[i] = nullptr;
}
data = nullptr;
std::swap(row, col);
// Присваиваем указатель на старое место
data = NewData;
}
void KbInput(int posX = 0, int posY = 0)
{
for (size_t i = 0; i < row; i++)
{
COORD coord;
coord.Y = i + 1 + posY;
for (size_t j = 0; j < col; j++)
{
if (j == 0) coord.X = j + 1 + posX;
bool flag;
do
{
int tmp;
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
std::cin >> tmp;
data[i][j] = tmp;
int size_tmpElem = std::to_string(tmp).size();
if (std::cin.fail())
{
std::cin.clear();
std::cin.ignore(32767, 'n');
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
for (size_t i = 0; i < 100; i++) std::cout << " ";
flag = true;
}
else
{
flag = false;
coord.X += size_tmpElem + 2;
}
} while (flag);
}
}
}
unsigned int getRow() const { return row; }
unsigned int getCol() const { return col; }
void DelRow(int pos)
{
if (pos < 0 || pos > row - 1) return;
type** NewData = new type * [row - 1];
createArr2D(NewData, row - 1, col);
if (pos != 0)
{
for (size_t i = 0; i < pos; i++)
{
for (size_t j = 0; j < col; j++)
{
NewData[i][j] = data[i][j];
}
}
}
for (size_t i = pos+1, i_posNew = pos; i < row ; i++, i_posNew++)
{
for (size_t j = 0, j_posNew = 0; j < col; j++, j_posNew++)
{
NewData[i_posNew][j_posNew] = data[i][j];
}
}
DeleteArr2D(data, row);
data = NewData;
row--;
}
void DelCol(int pos)
{
if (pos < 0 || pos > col - 1) return;
type** NewData;
createArr2D(NewData, row, col - 1);
if (pos != 0)
{
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < pos; j++)
{
NewData[i][j] = data[i][j];
}
}
}
for (size_t i = 0; i < row; i++)
{
for (size_t j = pos+1, j_NewData = pos; j < col; j++, j_NewData++)
{
NewData[i][j_NewData] = data[i][j];
}
}
DeleteArr2D(data, row);
data = NewData;
col--;
}
type findMaxElem()
{
type res = data[0][0];
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
if (data[i][j] > res) res = data[i][j];
}
}
return res;
}
type findMinElem()
{
type res = data[0][0];
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col; j++)
{
if (data[i][j] < res) res = data[i][j];
}
}
return res;
}
void lineByline_Sort()
{
for (size_t i = 0; i < row; i++)
{
for (size_t j = 0; j < col-1; j++)
{
int min = j;
for (size_t b = j+1; b < col; b++)
{
if (data[i][b] < data[i][min])
min = b;
}
std::swap(data[i][j], data[i][min]);
}
}
}
void Full_Sort()
{
for (size_t i_swap = 0; i_swap < row; i_swap++)
{
for (size_t j_swap = 0; j_swap < col; j_swap++)
{
int row_min = i_swap;
int col_min = j_swap;
for (size_t i = row_min; i < row; i++)
{
if (i == row_min)
{
for (size_t j = col_min + 1; j < col; j++)
{
if (data[i][j] < data[row_min][col_min])
{
row_min = i;
col_min = j;
}
}
}
else
{
for (size_t j = 0; j < col; j++)
{
if (data[i][j] < data[row_min][col_min])
{
row_min = i;
col_min = j;
}
}
}
}
std::swap(data[i_swap][j_swap], data[row_min][col_min]);
/*std::cout << std::endl << std::endl;
print();*/
}
}
}
};
|
holdem_ 0 / 0 / 0 Регистрация: 27.10.2018 Сообщений: 21 |
||||||||||||
|
1 |
||||||||||||
|
04.05.2019, 22:41. Показов 7472. Ответов 12 Метки ООП, шаблоны (Все метки)
При компиляции выдает ошибку : Ошибка C2760 синтаксическая ошибка: ожидался токен «спецификатор типа», а не «идентификатор» .
0 |
|
143 / 92 / 34 Регистрация: 30.01.2018 Сообщений: 469 |
|
|
04.05.2019, 22:44 |
2 |
|
В какой строке ошибка, а то просматривать весь код очень муторно
0 |
|
0 / 0 / 0 Регистрация: 27.10.2018 Сообщений: 21 |
|
|
04.05.2019, 22:49 [ТС] |
3 |
|
в 69 строке Добавлено через 51 секунду Добавлено через 48 секунд
0 |
|
143 / 92 / 34 Регистрация: 30.01.2018 Сообщений: 469 |
|
|
04.05.2019, 22:52 |
4 |
|
m_iArr = new init.T*[size_row]; Что такое init.T?
1 |
|
0 / 0 / 0 Регистрация: 27.10.2018 Сообщений: 21 |
|
|
04.05.2019, 23:02 [ТС] |
5 |
|
Что такое init.T? Да , просто T должно быть Добавлено через 2 минуты
Что такое init.T? Но когда делаю просто T , появляется
0 |
|
143 / 92 / 34 Регистрация: 30.01.2018 Сообщений: 469 |
|
|
04.05.2019, 23:04 |
6 |
|
Как у тебя сейчас 69 строка выглядит?
0 |
|
holdem_ 0 / 0 / 0 Регистрация: 27.10.2018 Сообщений: 21 |
||||
|
04.05.2019, 23:13 [ТС] |
7 |
|||
0 |
|
Pashka Durov 143 / 92 / 34 Регистрация: 30.01.2018 Сообщений: 469 |
||||
|
04.05.2019, 23:20 |
8 |
|||
|
Попробуй так
Но не гарантирую
0 |
|
holdem_ 0 / 0 / 0 Регистрация: 27.10.2018 Сообщений: 21 |
||||
|
05.05.2019, 11:52 [ТС] |
9 |
|||
|
Попробуй так
Но не гарантирую На 69 строку перестало ругаться , но всеравно есть ошибка в 72 строке : Добавлено через 1 минуту
0 |
|
5893 / 3296 / 1352 Регистрация: 07.02.2019 Сообщений: 8,325 |
|
|
05.05.2019, 11:56 |
10 |
|
holdem_, Просто скопируй цикл из строк 25-28.
0 |
|
0 / 0 / 0 Регистрация: 27.10.2018 Сообщений: 21 |
|
|
05.05.2019, 12:00 [ТС] |
11 |
|
holdem_, Просто скопируй цикл из строк 25-28. На эти строки тоже ругается .
0 |
|
zayats80888 5893 / 3296 / 1352 Регистрация: 07.02.2019 Сообщений: 8,325 |
||||
|
05.05.2019, 12:16 |
12 |
|||
|
На эти строки тоже ругается Матом? Добавлено через 11 минут
0 |
|
holdem_ 0 / 0 / 0 Регистрация: 27.10.2018 Сообщений: 21 |
||||
|
05.05.2019, 12:57 [ТС] |
13 |
|||
|
Матом? Добавлено через 11 минут
Все решил проблему — действительно не нужно реализовывать шаблонные классы по разным файлам . Всем спасибо за ответы
0 |
I’m trying to include the following definitions for GDI+ into my Win32 C++ project that is compiled under Visual Studio 2017:
#include <objidl.h>
#include <gdiplus.h>
#pragma comment (lib,"Gdiplus.lib")
I need to compile this project to support Windows XP. So in the project properies I selected: Platform Toolset as Visual Studio 2017 - Windows XP (v141_xp):

But when I compile it the GDI+ library gives me this:
1>c:program files (x86)microsoft sdkswindowsv7.1aincludeobjbase.h(239): error C2760: syntax error: unexpected token 'identifier', expected 'type specifier'
1>c:program files (x86)microsoft sdkswindowsv7.1aincludegdiplusheaders.h(891): error C4596: 'EmfToWmfBits': illegal qualified name in member declaration
1>c:program files (x86)microsoft sdkswindowsv7.1aincludegdiplusstringformat.h(220): error C4596: 'GetTrimming': illegal qualified name in member declaration
Any idea how to fix this?
asked Jul 12, 2019 at 22:41
1
Add this line before the very first(!) #include of COM-related header to fix objbase.h(239): error C2760: syntax error: unexpected token 'identifier', expected 'type specifier' :
typedef struct IUnknown IUnknown;
This fix works, because the line in objbase.h(239) mentioned in the error contains static_cast<IUnknown*>(*pp); despite that IUnknown still haven’t been declared in that place.
answered Jun 12, 2020 at 17:31
Кое КтоКое Кто
4495 silver badges9 bronze badges
I kinda got it to compile, but this is definitely not a good solution. I’m posting it here as a temp workaround until Microsoft gets their heads out of their ___es. Also if anyone finds a better way, please let me know.
I basically had to downgrade the entire project to Visual Studio 2015 - Windows XP (v140_xp) just to compile one badly written library:

This created a problem of its own with the std libraries:
1>C:Program Files (x86)Microsoft Visual Studio 14.0VCincludecstdio(50): error C4995: 'sprintf': name was marked as #pragma deprecated
1>C:Program Files (x86)Microsoft Visual Studio 14.0VCincludecstdio(53): error C4995: 'vsprintf': name was marked as #pragma deprecated
1>C:Program Files (x86)Microsoft Visual Studio 14.0VCincludecstring(20): error C4995: 'strcat': name was marked as #pragma deprecated
1>C:Program Files (x86)Microsoft Visual Studio 14.0VCincludecstring(21): error C4995: 'strcpy': name was marked as #pragma deprecated
1>C:Program Files (x86)Microsoft Visual Studio 14.0VCincludecwchar(29): error C4995: 'swprintf': name was marked as #pragma deprecated
1>C:Program Files (x86)Microsoft Visual Studio 14.0VCincludecwchar(30): error C4995: 'vswprintf': name was marked as #pragma deprecated
1>C:Program Files (x86)Microsoft Visual Studio 14.0VCincludecwchar(32): error C4995: 'wcscat': name was marked as #pragma deprecated
1>C:Program Files (x86)Microsoft Visual Studio 14.0VCincludecwchar(34): error C4995: 'wcscpy': name was marked as #pragma deprecated
So I had to shunt those errors of unsafe functions:
#pragma warning( push )
#pragma warning( disable: 4995 )
#include <stdio.h>
#include <new>
#include <string>
#pragma warning( pop )
Which is far from ideal!
(You’re basically sacrificing security of the app just to compile that damn GDI+ library.)
answered Jul 13, 2019 at 20:57
c00000fdc00000fd
20.7k27 gold badges175 silver badges392 bronze badges
1
There’s a way to get this to work if you’re prepared to edit the Windows header files.
In objbase.h, comment out line 239 or change it to:
static_assert (std::is_base_of <IUnknown *, *pp>::value, "pp must derive from IUnknown");
In gdiplusheaders.h, line 891, remove the redundant qualifier (Metafile::).
In gdiplusstringformat.h, line 220, remove the redundant qualifier (StringFormat::).
Hopefully, that will fix things for you without breaking anything.
answered Jul 13, 2019 at 23:23
Paul SandersPaul Sanders
23.7k4 gold badges26 silver badges48 bronze badges
1
Although the question is old, just adding what worked for me.
In my case including windows.h and compiling with VS2017 v141_xp toolset was causing me error: syntax error: unexpected token ‘identifier’, expected ‘type specifier’.
This resolved my issue link
answered Jul 15, 2021 at 15:43
![]()
Содержание
- Unity — Fix for Build Error C2760 in combaseapi.h — but still not working #1550
- Comments
- Библиотека GDI+ вызывает ошибку C2760: синтаксическая ошибка: неожиданный «идентификатор» токена, ожидаемый «описатель типа» в VS2017 при компиляции для XP
- Ответы (4)
- Библиотека GDI+ вызывает «ошибку C2760: синтаксическая ошибка: неожиданный токен» идентификатор «, ожидаемый» спецификатор типа «» в VS2017 при компиляции для XP
- 4 ответа
- Библиотека GDI + вызывает ошибку C2760: синтаксическая ошибка: неожиданный токен «идентификатор», ожидаемый «спецификатор типа» »в VS2017 при компиляции для XP
- Как создать проект C++, отличный от MFC, со статической привязкой к библиотекам времени выполнения VC?
Unity — Fix for Build Error C2760 in combaseapi.h — but still not working #1550
Hi, still can’t get the copter working. I did find a fix for the C2670 error though. Any thoughts appreciated.
Win 10 Home
Unity 2018.2.15f1
VS Community 2017 15.8.9
SDK 8.1
Unity/build.cmd Build fails with:
windows kits8.1includeumcombaseapi.h(229): error C2760: syntax error: unexpected token ‘identifier’, expected ‘type specifier’
1: Open (make backup first of course) C:Program Files (x86)Windows Kits8.1Includeumcombaseapi.h
2: Add struct IUnknown; // Workaround for «combaseapi.h(229): error C2187: syntax error: ‘identifier’ was unexpected here» when using /permissive-
3: Put this line at top of file above includes
4: Rebuild
5: Build succeeds but with warning:
«..PathAirSimUnityAirLibWrapperAirsimWrapper.sln» (Clean;Build target) (1) ->
«..PathAirSimUnityAirLibWrapperAirsimWrapperAirsimWrapper.vcxproj.metaproj» (default ta
rget) (2:2) ->
«..PathAirSimUnityAirLibWrapperAirsimWrapperAirsimWrapper.vcxproj» (default target) (5:
2) ->
(Link target) ->
LINK : warning LNK4075: ignoring ‘/INCREMENTAL’ due to ‘/LTCG’ specification [..PathAirSi
mUnityAirLibWrapperAirsimWrapperAirsimWrapper.vcxproj]
6: Run project SimModeSelector Unity Project Warning:
Cannot read settings file C:Program FilesUnityEditorsettings.json Vehicle=SimpleFlight
UnityEngine.Debug:LogError(Object)
AirSimUnity.Vehicle:PrintLogMessage(String, String, String, Int32) (at Assets/AirSimAssets/Scripts/Vehicles/Vehicle.cs:279)
AirSimUnity.VehicleCompanion:PrintLogMessage(String, String, String, Int32) (at Assets/AirSimAssets/Scripts/Vehicles/VehicleCompanion.cs:193)
7: Create settings.json file in Assets folder:
<
«SettingsVersion»: 1.2,
«SimMode»: «Multirotor»
>
8: Run Unity Project SimModeSelector. Copter does not respond to Page Up/Down & WASD
Car responds to WASD
The text was updated successfully, but these errors were encountered:
Источник
Библиотека GDI+ вызывает ошибку C2760: синтаксическая ошибка: неожиданный «идентификатор» токена, ожидаемый «описатель типа» в VS2017 при компиляции для XP
Я пытаюсь включить следующие определения для GDI+ в свой проект Win32 C++, скомпилированный в Visual Studio 2017:
Мне нужно скомпилировать этот проект для поддержки Windows XP. Итак, в свойствах проекта я выбрал: Platform Toolset как Visual Studio 2017 — Windows XP (v141_xp) :

Но когда я компилирую его, библиотека GDI+ дает мне это:
Есть идеи, как это исправить?
Ответы (4)
Добавьте эту строку перед самым первым (!) #include заголовком, связанным с COM, чтобы исправить objbase.h(239): error C2760: syntax error: unexpected token ‘identifier’, expected ‘type specifier’ :
Это исправление работает, потому что строка в objbase.h(239) , упомянутая в ошибке, содержит static_cast (*pp); , несмотря на то, что IUnknown еще не был объявлен в этом месте.
Я как бы получил его для компиляции, но это определенно не очень хорошее решение. Я публикую это здесь в качестве временного обходного пути, пока Microsoft не вылезет из головы. Также, если кто-то найдет лучший способ, пожалуйста, дайте мне знать.
По сути, мне пришлось понизить весь проект до Visual Studio 2015 — Windows XP (v140_xp) только для того, чтобы скомпилировать одну плохо написанную библиотеку:

Это создало собственную проблему с библиотеками std :
Поэтому мне пришлось шунтировать эти ошибки небезопасных функций:
Что далеко от идеала!
(По сути, вы жертвуете безопасностью приложения только для того, чтобы скомпилировать эту чертову библиотеку GDI+.)
Есть способ заставить это работать, если вы готовы редактировать заголовочные файлы Windows.
В objbase.h закомментируйте строку 239 или измените ее на:
В gdiplusheaders.h , строка 891, удалите лишний квалификатор ( Metafile:: ).
В gdiplusstringformat.h , строка 220, удалите лишний квалификатор ( StringFormat:: ).
Надеюсь, это исправит ситуацию для вас, ничего не сломав.
Хотя вопрос старый, просто добавляю то, что сработало для меня.
В моем случае включение windows.h и компиляция с набором инструментов VS2017 v141_xp вызывали у меня ошибку: синтаксическая ошибка: неожиданный «идентификатор» токена, ожидаемый «спецификатор типа».
Источник
Библиотека GDI+ вызывает «ошибку C2760: синтаксическая ошибка: неожиданный токен» идентификатор «, ожидаемый» спецификатор типа «» в VS2017 при компиляции для XP
Я пытаюсь включить следующие определения для GDI+ в мой проект Win32 C++, который скомпилирован в Visual Studio 2017:
Мне нужно скомпилировать этот проект для поддержки Windows XP. Поэтому в свойствах проекта я выбрал: Platform Toolset как Visual Studio 2017 — Windows XP (v141_xp) :

Но когда я компилирую это, библиотека GDI+ дает мне это:
Есть идеи как это исправить?
4 ответа
Добавьте эту строчку перед самым первым (!) #include заголовка, связанного с COM, чтобы исправить objbase.h(239): error C2760: syntax error: unexpected token ‘identifier’, expected ‘type specifier’ :
Это исправление работает, потому что строка в objbase.h(239) упомянутый в ошибке содержит static_cast (*pp); несмотря на то, что IUnknown до сих пор не объявлен в этом месте.
Я вроде получил его для компиляции, но это определенно не хорошее решение. Я опубликую его здесь как временное решение, пока Microsoft не избавится от своих ___ идей. Также, если кто-нибудь найдет лучший способ, пожалуйста, дайте мне знать.
Я в основном должен был понизить весь проект до Visual Studio 2015 — Windows XP (v140_xp) просто скомпилировать одну плохо написанную библиотеку:

Это создало собственную проблему с std библиотеки:
Таким образом, я должен был избежать ошибок небезопасных функций:
Что далеко от идеала!
(Вы в основном жертвуете безопасностью приложения, просто чтобы скомпилировать эту чертову библиотеку GDI+.)
Есть способ заставить это работать, если вы готовы редактировать заголовочные файлы Windows.
В objbase.h закомментируйте строку 239 или измените ее на:
В gdiplusheaders.h , строка 891, удалите лишний квалификатор ( Metafile:: ).
В gdiplusstringformat.h , строка 220, удалите лишний классификатор ( StringFormat:: ).
Надеюсь, это исправит ситуацию, не сломав ничего.
Хотя вопрос старый, просто добавляю то, что сработало для меня.
В моем случае включение windows.h и компиляция с набором инструментов VS2017 v141_xp вызывали у меня ошибку: синтаксическая ошибка: неожиданный «идентификатор» токена, ожидаемый «описатель типа».
Источник
Библиотека GDI + вызывает ошибку C2760: синтаксическая ошибка: неожиданный токен «идентификатор», ожидаемый «спецификатор типа» »в VS2017 при компиляции для XP
Я пытаюсь включить следующие определения для GDI + в свой проект Win32 C ++, который скомпилирован в Visual Studio 2017:
Мне нужно скомпилировать этот проект для поддержки Windows XP. Итак, в выбранном мной проекте свойства: Platform Toolset как Visual Studio 2017 — Windows XP (v141_xp) :

Но когда я его компилирую, библиотека GDI + дает мне следующее:
Есть идеи, как это исправить?
Добавьте эту строку перед самым первым (!) #include Заголовком, связанным с COM, чтобы исправить objbase.h(239): error C2760: syntax error: unexpected token ‘identifier’, expected ‘type specifier’ :
Это исправление работает, потому что строка, objbase.h(239) упомянутая в ошибке, содержит, static_cast (*pp); несмотря на то, что IUnknown еще не был объявлен в этом месте.
Мне удалось его скомпилировать, но это определенно не лучшее решение. Я публикую это здесь как временный обходной путь, пока Microsoft не избавится от своих ___es. Также, если кто-нибудь найдет способ получше, дайте мне знать.
Мне в основном пришлось понизить версию всего проекта, чтобы Visual Studio 2015 — Windows XP (v140_xp) просто скомпилировать одну плохо написанную библиотеку:

Это создало собственную проблему с std библиотеками:
Поэтому мне пришлось устранить эти ошибки небезопасных функций:
Что далеко не идеально!
(По сути, вы жертвуете безопасностью приложения только для того, чтобы скомпилировать эту чертову библиотеку GDI +.)
Источник
Как создать проект C++, отличный от MFC, со статической привязкой к библиотекам времени выполнения VC?
Я знаю, что для проекта MFC, созданного с помощью Visual Studio, можно перейти в свойства проекта, а затем Configuration Properties -> General -> use of MFC и изменить его на Use MFC in a static library :

Это работает, если полученная сборка должна запускаться в более ранних версиях Windows без необходимости установки DLL времени выполнения MFC или VC. Полученная сборка будет использовать библиотеки DLL, которые уже присутствуют в каждой установке Windows, начиная с Windows 7 и выше. (Возможно, даже до Windows XP.)
Теперь, если я создаю проект без MFC, скажем, тестовое консольное приложение C++, параметр для использования MFC настроен как «Использовать стандартные библиотеки Windows»:

Но если я запустил полученный двоичный файл, скажем, при новой установке Windows 7, я получаю такую ошибку:

Итак, покопавшись в настройках, я не смог найти способ скомпилировать его со статической привязкой ко всем этим новым версиям библиотек VC RT. Он есть, а я его просто не вижу?
PS. Покопавшись дальше, я обнаружил, что могу изменить «Platform Toolset» на Visual Studio 2017 — Windows XP (v141_xp) , предполагая, что это сделает его обратно совместимым с Windows XP и выше:

Но затем, если я его скомпилирую, я получаю следующие ошибки:
В этой части файла ObjBase.h , который не имеет ничего общего с моим тестовым консольным проектом C++, который я только что создал из шаблона Visual Studio:

Итак, мой вопрос: могу ли я создать проект на C++, отличный от MFC, который может работать в более старых версиях Windows без необходимости установки VC Runtime или каких-либо других дополнительных библиотек?
Источник
Сообщение об ошибке сообщает вам, что вы можете сделать:
typename std::map<std::string, _Value>::iterator itr = this->begin();
// ^^^^^^^^^
… но не потому, что вам нужно.
Короче говоря, это причуда C++, относящаяся к шаблонам и так называемым «зависимым именам». Поскольку _Value является параметром шаблона, и поскольку существует специализированная специализация шаблона, C++ не может точно знать, что std::map<std::string, _Value> имеет iterator типа члена, пока немного позже в процессе синтаксического анализа. Таким образом, ваша декларация плохо сформирована, потому что компилятор не может воспринимать ее как декларацию, даже если она скривится. typename говорит, что «это будет тип, я обещаю», а затем все отлично (пока это окажется типом!).
Вы можете подумать, что это должна быть проблема C++, а не ваша, и вы, вероятно, будете правы, но это так, как есть. Вы можете найти дополнительную информацию об этом или просто считать само собой разумеющимся, что, когда компилятор говорит вам написать typename, вы пишете typename.
С другой стороны, сделать код лучше и решить эту проблему, в то же время, с помощью auto вместо этого:
auto itr = this->begin();
Кстати, ваш код подсказывает, что вы используете неправильный контейнер, GetItem должен быть const, вы должны использовать cbegin() not begin() (хотя это для вас сделано, если вы следуете предложению const) и std::advance уже существует…
Solution 1
You can fix it in such ways:
typename std::map<std::string, _Value>::iterator itr = this->begin();
or
auto itr = this->begin();
Solution 2
The error message tells you exactly what you can do:
typename std::map<std::string, _Value>::iterator itr = this->begin();
// ^^^^^^^^^
… but not why you have to.
In short, this is a quirk of C++ relating to templates and so-called «dependent names». Because _Value is a template parameter, and because template specialisation exists, C++ can’t know for sure that std::map<std::string, _Value> has a member type iterator until a little later in the parsing process. As such, your declaration is ill-formed because the compiler can’t quite see it as a declaration even if it squints. typename says «this is going to be a type, I promise» and then everything’s fine (as long as it does turn out to be a type!).
You may think that this should be C++’s problem, rather than yours, and you’d probably be right, but that’s just the way it is. You can search for more information on this or just take it for granted that when the compiler tells you to write typename, you write typename.
Alternatively, make your code nicer and solve the problem at the same time, by using auto instead:
auto itr = this->begin();
By the way, your code suggests that you’re using the wrong container, GetItem should be const, you should use cbegin() not begin() (though this is sort of done for you if you follow the const suggestion), and std::advance already exists…
Solution 3
To fix the error, you can either follow the hint given by the compiler or change the line into
auto itr = this->begin();
While overusing auto is questionable, it’s usually considered ok for iterator types; return types of begin() and end() member functions are common (and sometimes complicated) enough to not type the exact type.
A further side note: GetItem can use a const_iterator, too, and hence auto itr = this->cbegin(); would be an improvement.
Related videos on Youtube

02 : 28
How to Fix Uncaught SyntaxError: Unexpected token ‘{‘

01 : 30
Parse error: syntax error, unexpected } PHP Solved

03 : 26
syntax error on token . @ expected after this token

03 : 59
unexpected identifier and unexpected token errors in NodeJs

01 : 34
Parse error: syntax error, unexpected ‘index’ (T_STRING), expecting ‘,’ or ‘;’ in C:xampp (fixed)

04 : 00
FatalErrorException in Inflector.php line 265: syntax error, unexpected ‘:’, expecting ‘;’ or ‘{‘

01 : 23
syntax error unexpected token — CSS
Comments
-
I had created a class inheriting
std::mapand trying to get value at particular index using an method.#define MYAPI_EXPORTS #ifdef MYAPI_EXPORTS #define MY_API __declspec(dllexport) #else #define MY_API __declspec(dllimport) #endif template<class _Value> class MY_API MyDictionary : public std::map<std::string, _Value> { _Value GetItem(int index) { std::map<std::string, _Value>::iterator itr = this->begin(); //compile error at this line int c = 0; while (c < index) { itr++; c++; } return itr->second; } };‘std::map::iterator itr’ this line shows error while compiling.
the errors are
error C2760: syntax error: unexpected token 'identifier', expected ';' error C7510: 'iterator': use of dependent type name must be prefixed with 'typename'It seems like iterator type is not defined in compile time. Is there any solution to fix this?
-
use of dependent type name must be prefixed with 'typename'. -
you are using a
mapas if it was avector. Ifindexwas the key you could use the mapsoperator[] -
You just need to put
typenamebeforestd::map<std::string, _Value>::iterator itr -
how to use typename before std::map<std::string, _Value>::iterator itr ?
-
Obligatory comment: Using
_Valueas identifier is undefined behavior. All identifiers beginning with underscore and a capital letter are reserved for the implementation (as are any identifiers beginning with two underscores).
-

