Ошибка c2589 недопустимая лексема справа от

When I try to compile some code (not my own) i get a C2589 ‘(‘:illegal token on right side of’::’

on this line:

    maxPosition[0]=std::numeric_limits<double>::min();

i guess this is because there is already a min() macro defined, but why is the compiler not taking the min() from the specified namespace instead of the macro?

Phil Miller's user avatar

Phil Miller

36.2k13 gold badges67 silver badges89 bronze badges

asked Dec 1, 2009 at 12:29

Mat's user avatar

3

but why is the compiler not taking the min() from the specified namespace instead of the macro?

Because macros don’t care about your namespaces, language semantics, or your compiler. The preprocessing happens first.

In other words, the compiler only sees what is left after the preprocessing stage. And min was replaced by some replacement string, and the result is what the compiler saw.

answered Dec 15, 2009 at 2:28

Alex Budovski's user avatar

Alex BudovskiAlex Budovski

17.9k6 gold badges53 silver badges58 bronze badges

Hitting F12 on offending std::numeric_limits::min() function

Leads to some where like :

c:Program Files (x86)Windows Kits8.1Includesharedminwindef.h

Where you will find:

#ifndef NOMINMAX

#ifndef max
#define max(a,b)            (((a) > (b)) ? (a) : (b))
#endif

#ifndef min
#define min(a,b)            (((a) < (b)) ? (a) : (b))
#endif

So adding

#define NOMINMAX

to top of your .cpp file (as the WINAPI does: see Windows.h as example) before any #include headers should rectify the problem.

answered Mar 22, 2019 at 15:19

bitminer's user avatar

3

add this to the top of your file. I’m pretty sure it’s just a bug in the way the linker works in Visual studio. You sometimes get this whenever you have an operator overload.

using namespace std;

in my case this works

 for (int i = min(size_used_, other.size_used_) - 1; i >= 0; --i) {
  result += data_[i] * other.data_[i];
}

when this does not

 for (int i = std::min(size_used_, other.size_used_) - 1; i >= 0; --i) {
  result += data_[i] * other.data_[i];
}

answered Jul 9, 2019 at 23:44

steveoams's user avatar

steveoamssteveoams

4044 silver badges6 bronze badges

Sorato

0 / 0 / 0

Регистрация: 09.03.2019

Сообщений: 9

1

09.03.2019, 12:03. Показов 11144. Ответов 15

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

При компиляции Visual Studio 2017 жалуется на эти строчки из библиотеки SFML

C++
1
 T minX = std::min(left, static_cast<T>(left + width));

и

C++
1
 T r1MinX = std::min(left, static_cast<T>(left + width));

Ошибка — C2589 (: недопустимая лексема справа от «::»



0



eva2326

1464 / 396 / 86

Регистрация: 17.05.2015

Сообщений: 1,304

09.03.2019, 13:26

2

Цитата
Сообщение от Sorato
Посмотреть сообщение

std::min

В настройках проекта объявите дефайн препроцессора: NOMINMAX

Либо перед включением хедеров SFML напишите:

C++
1
#define NOMINMAX



1



0 / 0 / 0

Регистрация: 09.03.2019

Сообщений: 9

09.03.2019, 13:57

 [ТС]

3

Не помогло



0



FFPowerMan

2023 / 1127 / 475

Регистрация: 11.10.2018

Сообщений: 5,734

09.03.2019, 14:02

4

C++
1
#include <algorithm>

— вот это, наверное, забыли написать.



0



0 / 0 / 0

Регистрация: 09.03.2019

Сообщений: 9

10.03.2019, 12:38

 [ТС]

5

#define NOMINMAX — есть
#include <algorithm> — есть
Ошибка — есть



0



Неэпический

17819 / 10592 / 2044

Регистрация: 27.09.2012

Сообщений: 26,636

Записей в блоге: 1

11.03.2019, 11:00

6

Минимальный код, демонстрирующий проблему приведите.



0



Sorato

0 / 0 / 0

Регистрация: 09.03.2019

Сообщений: 9

11.03.2019, 17:15

 [ТС]

7

C++
1
2
3
4
5
6
7
8
9
10
11
12
bool Rect<T>::contains(T x, T y) const
{
    // Rectangles with negative dimensions are allowed, so we must handle them correctly
 
    // Compute the real min and max of the rectangle on both axes
    T minX = std::min(left, static_cast<T>(left + width));
    T maxX = std::max(left, static_cast<T>(left + width));
    T minY = std::min(top, static_cast<T>(top + height));
    T maxY = std::max(top, static_cast<T>(top + height));
 
    return (x >= minX) && (x < maxX) && (y >= minY) && (y < maxY);
}

и

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
bool Rect<T>::intersects(const Rect<T>& rectangle, Rect<T>& intersection) const
{
    // Rectangles with negative dimensions are allowed, so we must handle them correctly
 
    // Compute the min and max of the first rectangle on both axes
    T r1MinX = std::min(left, static_cast<T>(left + width));
    T r1MaxX = std::max(left, static_cast<T>(left + width));
    T r1MinY = std::min(top, static_cast<T>(top + height));
    T r1MaxY = std::max(top, static_cast<T>(top + height));
 
    // Compute the min and max of the second rectangle on both axes
    T r2MinX = std::min(rectangle.left, static_cast<T>(rectangle.left + rectangle.width));
    T r2MaxX = std::max(rectangle.left, static_cast<T>(rectangle.left + rectangle.width));
    T r2MinY = std::min(rectangle.top, static_cast<T>(rectangle.top + rectangle.height));
    T r2MaxY = std::max(rectangle.top, static_cast<T>(rectangle.top + rectangle.height));
 
    // Compute the intersection boundaries
    T interLeft   = std::max(r1MinX, r2MinX);
    T interTop    = std::max(r1MinY, r2MinY);
    T interRight  = std::min(r1MaxX, r2MaxX);
    T interBottom = std::min(r1MaxY, r2MaxY);
 
    // If the intersection is valid (positive non zero area), then there is an intersection
    if ((interLeft < interRight) && (interTop < interBottom))
    {
        intersection = Rect<T>(interLeft, interTop, interRight - interLeft, interBottom - interTop);
        return true;
    }
    else
    {
        intersection = Rect<T>(0, 0, 0, 0);
        return false;
    }
}



0



Неэпический

17819 / 10592 / 2044

Регистрация: 27.09.2012

Сообщений: 26,636

Записей в блоге: 1

11.03.2019, 17:56

8

И? Я вот это возьму, вставлю в студийный проект и получу 100500 ошибок, никак не связанных с текущей темой.



0



Antikl

с++

1282 / 523 / 225

Регистрация: 15.07.2015

Сообщений: 2,562

11.03.2019, 20:14

9

у тебя так работает?

C++
1
int interLeft   = std::max(56, 76);

или

C++
1
int interLeft   = max(56, 76);



0



Sorato

0 / 0 / 0

Регистрация: 09.03.2019

Сообщений: 9

12.03.2019, 16:10

 [ТС]

10

Добавлено через 1 минуту
Если вы имели ввиду мой код, то вот

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
#include "stdafx.h"
#include <SFML/Graphics.hpp>
#include <algorithm>
 
#define NOMINMAX
 
 
using namespace std;
using namespace sf;
 
int main()
{
    RenderWindow window(VideoMode(200, 200), "SFMLworks");
    CircleShape shape(100.f);
    shape.setFillColor(Color::Green);
 
    while (window.isOpen())
    {
        Event event;
        while (window.pollEvent(event))
        {
            if (event.type == Event::Closed)
                window.close();
        }
 
        window.clear();
        window.draw(shape);
        window.display();
    }
 
    return 0;
}



0



Неэпический

17819 / 10592 / 2044

Регистрация: 27.09.2012

Сообщений: 26,636

Записей в блоге: 1

12.03.2019, 17:26

11

Sorato, написали же, добавить NOMINMAX ДО ВКЛЮЧЕНИЯ заголовков.



0



Antikl

с++

1282 / 523 / 225

Регистрация: 15.07.2015

Сообщений: 2,562

12.03.2019, 22:50

12

Цитата
Сообщение от Sorato
Посмотреть сообщение

C++
1
2
using namespace std;
using namespace sf;

автор sfml не рекомендует использовать так как это может вызвать мноожество ошибок, про с++ думаю так же



0



0 / 0 / 0

Регистрация: 09.03.2019

Сообщений: 9

13.03.2019, 15:16

 [ТС]

13

ДОБАВЛЯЛ, до включения заголовков, но проблема остаётся!

Добавлено через 1 минуту

Цитата
Сообщение от Antikl
Посмотреть сообщение

автор sfml не рекомендует использовать так как это может вызвать мноожество ошибок, про с++ думаю так же

смотрел ролик по работе с SFML, автор использовал эти строки и ошибок у него не было



0



Неэпический

17819 / 10592 / 2044

Регистрация: 27.09.2012

Сообщений: 26,636

Записей в блоге: 1

13.03.2019, 16:59

14

Sorato, никому не интересна мистика.
Вы привели код, в котором продемонстрировали,
что написано не так как должно.
А если NOMINMAX добавить до включения заголовков,
то в данном коде вылезет другая проблема.



0



с++

1282 / 523 / 225

Регистрация: 15.07.2015

Сообщений: 2,562

13.03.2019, 18:11

15

Цитата
Сообщение от Sorato
Посмотреть сообщение

смотрел ролик по работе с SFML, автор использовал эти строки и ошибок у него не было

какой ролик? я попробывал все у меня работает, код выкладывай ничего не ясно что там твориться в вашем проекте



0



0 / 0 / 0

Регистрация: 09.03.2019

Сообщений: 9

13.03.2019, 22:14

 [ТС]

16

Проблема решена.
ЗАКРЫТО



0



When I try to compile some code (not my own) i get a C2589 ‘(‘:illegal token on right side of’::’

on this line:

    maxPosition[0]=std::numeric_limits<double>::min();

i guess this is because there is already a min() macro defined, but why is the compiler not taking the min() from the specified namespace instead of the macro?

Phil Miller's user avatar

Phil Miller

36.2k13 gold badges67 silver badges89 bronze badges

asked Dec 1, 2009 at 12:29

Mat's user avatar

3

but why is the compiler not taking the min() from the specified namespace instead of the macro?

Because macros don’t care about your namespaces, language semantics, or your compiler. The preprocessing happens first.

In other words, the compiler only sees what is left after the preprocessing stage. And min was replaced by some replacement string, and the result is what the compiler saw.

answered Dec 15, 2009 at 2:28

Alex Budovski's user avatar

Alex BudovskiAlex Budovski

17.9k6 gold badges53 silver badges58 bronze badges

Hitting F12 on offending std::numeric_limits::min() function

Leads to some where like :

c:Program Files (x86)Windows Kits8.1Includesharedminwindef.h

Where you will find:

#ifndef NOMINMAX

#ifndef max
#define max(a,b)            (((a) > (b)) ? (a) : (b))
#endif

#ifndef min
#define min(a,b)            (((a) < (b)) ? (a) : (b))
#endif

So adding

#define NOMINMAX

to top of your .cpp file (as the WINAPI does: see Windows.h as example) before any #include headers should rectify the problem.

answered Mar 22, 2019 at 15:19

bitminer's user avatar

3

add this to the top of your file. I’m pretty sure it’s just a bug in the way the linker works in Visual studio. You sometimes get this whenever you have an operator overload.

using namespace std;

in my case this works

 for (int i = min(size_used_, other.size_used_) - 1; i >= 0; --i) {
  result += data_[i] * other.data_[i];
}

when this does not

 for (int i = std::min(size_used_, other.size_used_) - 1; i >= 0; --i) {
  result += data_[i] * other.data_[i];
}

answered Jul 9, 2019 at 23:44

steveoams's user avatar

steveoamssteveoams

4044 silver badges6 bronze badges

Просмотр 4 сообщений — с 1 по 4 (из 4 всего)

  • Автор

    Сообщения

  • XdubHaosX
    XdubHaosX

    Участник

    Сообщений:25

    Зарегистрирован:
    14.11.2015

    Репутация:14

    Не могу создать взаимодействие 2 объектов, выбивает такую ошибку:
    Ошибка 11 error C2589: (: недопустимая лексема справа от “::” f:projects c++abandonedgame by xdubhaosxsfml-2.3.2includesfmlgraphicsrect.inl 116 1 ABANDONED

    for (Pobj_Interaction_1 = Pobjects.begin(); Pobj_Interaction_1 != Pobjects.end(); Pobj_Interaction_1++) {

    PObjects *it_1 = *Pobj_Interaction_1;

    // Взаимодействие объектов

    for (Pobj_Interaction_2 = Pobjects.begin(); Pobj_Interaction_2 != Pobjects.end(); Pobj_Interaction_2++) {

    PObjects *it_2 = *Pobj_Interaction_2;

    if ((it_1->Object_Name == «XdubHaosX») && (it_2->Object_Name == «Orl»))

    <strong> if (it_1->Get_Object().intersects(it_2->Get_Object())) {

    cout << «1»;

    }</strong>

    }

    RazorNd
    RazorNd

    Участник

    Сообщений:46

    Зарегистрирован:
    04.02.2016

    Репутация:38

    Попробуй добавить после include секции этого cpp-файла эти строки:


    udyzy

    Участник

    Сообщений:1

    Зарегистрирован:
    03.01.2020

    Репутация:0

    szyku ewenementów sumpt montażu okrążenia okrążenie natomiast furtkę egzystuje natłok gorszy niżby dojrzalsza naprawa. sztachety plastikowe Lecz ogrodzenia asystują więcej zwierzętami jakie zdołałyby popsuć rośliny posiane z plastyku obramowanie i furtę mogą funkcjonowań dodatkowo klawą profilaktyką od zefirka także pyle.


    iruduce

    Участник

    Сообщений:1

    Зарегистрирован:
    04.02.2020

    Репутация:0

    Rozgraniczenia skazańcu reanimować dzierżawę homo szubrawcami. sztachety plastikowe konin Okrążenia podlegają dodatkowo końcowego dostarczają jednostronnym magnatom poprzez rozwlekły termin.

  • Автор

    Сообщения

Просмотр 4 сообщений — с 1 по 4 (из 4 всего)

Для ответа в этой теме необходимо авторизоваться.

нет ошибки:

#include "pch.h"
//#include <windows.h>
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace sf;
using namespace std;
int main()
{

sf::RenderWindow window(sf::VideoMode(640, 480), "Lesson");
    return 0;
}

есть ошибка:

#include "pch.h"
#include <windows.h>
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace sf;
using namespace std;
int main()
{

sf::RenderWindow window(sf::VideoMode(640, 480), "Lesson");
    return 0;
}

Ошибка C2589 (: недопустимая лексема справа от «::» q2222 c:libssfml-2.5.1x86includesfmlgraphicsrect.inl

Почему то windows.h и sfml не хотят в паре работать.Хотя по отдельности пашут.Почему?

  • Ошибка c2550 kyocera 3501i
  • Ошибка c2540 prius 10
  • Ошибка c2447 отсутствует заголовок функции возможно используется формальный список старого типа
  • Ошибка c2433 ostream friend не разрешается для объявлений данных
  • Ошибка c2429 для функция языка структурированные привязки нужен флаг компилятора std c 17