Error c2589 illegal token on right side of

I have the following template declaration: template void IterTable(int& rIdx, std::vector& rVarVector, ...

I have the following template declaration:

template <typename T>
   void IterTable(int&                       rIdx,
                  std::vector<double>&       rVarVector,
                  const std::vector<T>&      aTable,
                  const T                    aValue,
                  T              aLowerBound = -(std::numeric_limits<T>::max()), //illegal token on right side of '::' shows here
                  bool                       aLeftOpen = true) const;

Which throws the illegal token error as noted, on the line with «-(std::numeric_limits::max())». I got this code from some old linux source that I’m trying to compile on Windows. Any idea what the issue is?

Edit: It also fails using min(), and the compiler output is:

Error   92  error C2589: '::' : illegal token on right side of '::' c:projectsr&dprepaydllincludecfcdefault.h  216 PrepayDLL

Error   93  error C2059: syntax error : '::'    c:projectsr&dprepaydllincludecfcdefault.h  216 PrepayDLL

Line 216, is the line previously mentioned.

#define NOMINMAX

#include «stdafx.h»
#include <vector>
#include <limits>

#include «Win32Project1.h»

#include <SFML/Graphics.hpp>
#include <iostream>

bool intersects(const sf::RectangleShape & r1, const sf::RectangleShape & r2){
        sf::FloatRect snake = r1.getGlobalBounds();
        sf::FloatRect spawnedFruit = r2.getGlobalBounds();
        return snake.intersects(spawnedFruit);

}

sf::RectangleShape generateFruit() {

        sf::RectangleShape fruit;
        fruit.setFillColor(sf::Color::Yellow);
        int fruitx = rand() % 400;
        int fruity = rand() % 400;
        fruit.setPosition(fruitx, fruity);
        fruit.setSize(sf::Vector2f(5, 5));

        return fruit;

}
int main()
{
        srand(time(NULL));
        int width = 400;
        int height = 400;
        sf::VideoMode videomode(width, height);
        sf::RenderWindow window(videomode, «Snake»);
        sf::RectangleShape snake;

        snake.setFillColor(sf::Color::Red);
        snake.setSize(sf::Vector2f(20, 20));
        snake.setPosition(100, 100);
        sf::Clock clock;
        sf::Time t1 = sf::seconds(20);
        sf::RectangleShape spawnedFruit;
        while (window.isOpen()) {
                window.clear();
                window.draw(snake);

                sf::Time elapsed1 = clock.getElapsedTime();
                if (elapsed1 >= t1) {

                        spawnedFruit = generateFruit();

                        clock.restart();

                }

                window.draw(spawnedFruit);

                window.display();
                sf::Event event;
                while (window.pollEvent(event))
                {
                        if ((event.type == sf::Event::Closed) ||
                                ((event.type == sf::Event::KeyPressed) && (event.key.code == sf::Keyboard::Escape)))
                                window.close();
                }

                if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))

                        snake.move(0, 0.1);
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
                        snake.move(0, 0.1);
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
                        snake.move(0.1, 0);
                else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
                        snake.move(0.1, 0);
                if (intersects(snake, spawnedFruit))
                        std::cout << «Intersects»;

        }

}

////////////////////////////////////////////////////////////
//
// SFML — Simple and Fast Multimedia Library
// Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org)
//
// This software is provided ‘as-is’, without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
//    you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment
//    in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
//    and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////
template <typename T>
Rect<T>::Rect() :
left  (0),
top   (0),
width (0),
height(0)
{

}

////////////////////////////////////////////////////////////
template <typename T>
Rect<T>::Rect(T rectLeft, T rectTop, T rectWidth, T rectHeight) :
left  (rectLeft),
top   (rectTop),
width (rectWidth),
height(rectHeight)
{

}

////////////////////////////////////////////////////////////
template <typename T>
Rect<T>::Rect(const Vector2<T>& position, const Vector2<T>& size) :
left  (position.x),
top   (position.y),
width (size.x),
height(size.y)
{

}

////////////////////////////////////////////////////////////
template <typename T>
template <typename U>
Rect<T>::Rect(const Rect<U>& rectangle) :
left  (static_cast<T>(rectangle.left)),
top   (static_cast<T>(rectangle.top)),
width (static_cast<T>(rectangle.width)),
height(static_cast<T>(rectangle.height))
{
}

////////////////////////////////////////////////////////////
template <typename T>
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);
}

////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::contains(const Vector2<T>& point) const
{
    return contains(point.x, point.y);
}

////////////////////////////////////////////////////////////
template <typename T>
bool Rect<T>::intersects(const Rect<T>& rectangle) const
{
    Rect<T> intersection;
    return intersects(rectangle, intersection);
}

////////////////////////////////////////////////////////////
template <typename T>
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)); //problems start here
    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;
    }
}

////////////////////////////////////////////////////////////
template <typename T>
inline bool operator ==(const Rect<T>& left, const Rect<T>& right)
{
    return (left.left == right.left) && (left.width == right.width) &&
           (left.top == right.top) && (left.height == right.height);
}

////////////////////////////////////////////////////////////
template <typename T>
inline bool operator !=(const Rect<T>& left, const Rect<T>& right)
{
    return !(left == right);
}

I get the errors:-
Error   9   error C2059: syntax error : ‘::’
Error   10   error C2589: ‘(‘ : illegal token on right side of ‘::’
 and that till line 130 (in VS)

Forum Updated on Feb 6th

This topic has been deleted. Only users with topic management privileges can see it.

  • I’m working on porting an existing project which was originally developed for Qt 4.8. I have porting this to Qt 5.8 and updating various other libraries to later revisions.

    I’m getting the error C2589 during compile on:

    QList<double>& groupList = m_sampleHistory[group];
    if(groupList.size() == 0) {
        groupList.push_back(0.0);
    }
    groupList.back() = std::max(groupList.back(), sample);
    

    The error is shown on the last line above. I didn’t write this code and it doesn’t look correct as back() returns a ‘const double&’. The headers that are include are:

    #include "win.h"
    #include <algorithm>
    #include <iostream>
    #include <string>
    
    #include "QVariant"
    #include "QMap"
    #include "QList"
    #include "QString"
    #include "boost/array.hpp"
    

    win.h is a header I created which contains:

    #ifndef WIN_H
        #define WIN_H
    
        #ifndef AF_IPX
            #ifndef WIN32_LEAN_AND_MEAN
               #define WIN32_LEAN_AND_MEAN 1
            #endif
            #ifndef WIN32
                #define WIN32
            #endif
            #include <stdio.h>
            #include <stdlib.h>
            #include <WinSock2.h>
            #include <Windows.h>
        #endif
    #endif
    
  • @sierdzio , also just tried your example and it won’t allow it:

    const double existing = groupList.takeLast();
    groupList.append(std::max(existing, sample));
    

    The last line has exclamantion mark on it , the errors are:

    error: C2589: '(' : illegal token on right side of '::'    
    error: C2143: syntax error : missing ')' before '::'
    error: C2661: 'QList<double>::append' : no overloaded function takes 0 arguments
    error: C2059: syntax error : ')'
    

    All of those on that line. Having just looked at the details on QList, I can see that the const version of back is an overloaded version, there is also an identical version without const.
    In the end, this works:

    double last = groupList.takeLast();
    
    if ( sample > last )
        last = sample;
    groupList.last() = last;
    
  • @SPlatten said in error C2589: ‘(‘ : illegal token on right side of ‘::’:

    groupList.back()

    Try this:

    const double existing = groupList.takeLast();
    groupList.append(std::max(existing, sample));
    

    although it returns the same value.

    It’s not as efficient, perhaps, but more readable. And should compile ;-)

  • @sierdzio , thanks , to me the logic just doesn’t look right I have it compiling now, somehow its assigning a value to a const double reference.

    The error has now changed, now I’m getting:

    ocidl.h(45) : error C2146: syntax error : missing ';' before identifier
    
  • Is sample also a double? Perhaps std::max gets confused.

  • @sierdzio , yes, passed in as const double.

  • @sierdzio , also just tried your example and it won’t allow it:

    const double existing = groupList.takeLast();
    groupList.append(std::max(existing, sample));
    

    The last line has exclamantion mark on it , the errors are:

    error: C2589: '(' : illegal token on right side of '::'    
    error: C2143: syntax error : missing ')' before '::'
    error: C2661: 'QList<double>::append' : no overloaded function takes 0 arguments
    error: C2059: syntax error : ')'
    

    All of those on that line. Having just looked at the details on QList, I can see that the const version of back is an overloaded version, there is also an identical version without const.
    In the end, this works:

    double last = groupList.takeLast();
    
    if ( sample > last )
        last = sample;
    groupList.last() = last;
    
  • @SPlatten said in error C2589: ‘(‘ : illegal token on right side of ‘::’:

    double last = groupList.takeLast();

    if ( sample > last )
    last = sample;
    groupList.last() = last;

    I am not sure this is the same as groupList.back() = std::max(groupList.back(), sample);

    I think your should change to

    double last = groupList.takeLast();
    
    if ( sample > last )
         last = sample;
    groupList.insert(last);
    

    or

    groupList.insert(std::max(groupList.takeLast(), double(sample)));
    
  • @KroMignon , the original code was setting last in the same way, I’ve just kept it the same.

  • @SPlatten said in error C2589: ‘(‘ : illegal token on right side of ‘::’:

    , I’ve just kept it the same.

    No, you don’t.
    You take the last element from the list with QList::takeLast(). So your list will be 1 item shorter as begin.

  • @KroMignon , the original code, which would compile:

    groupList.back() = std::max(groupList.back(), sample);
    

    The replacement:

    double last = groupList.takeLast();
    
    if ( sample > last )
        last = sample;
    groupList.last() = last;
    

    How is the new code different from the original, except now it compiles?

  • @SPlatten said in error C2589: ‘(‘ : illegal token on right side of ‘::’:

    How is the new code different from the original, except now it compiles?

    You now overwrite the element before the last element: say you have 3 elements [A, B, C].
    After takeLast() you have [A, B].
    If you now execute groupList.last() = last; you will overwrite B.

  • @jsulm , thank you, and the original just overrides the last item without removing it?

    So if I just change it to:

    double last = groupList.last();
    
    if ( sample > last )
        last = sample;
    groupList.last() = last;
    
  • @SPlatten said in error C2589: ‘(‘ : illegal token on right side of ‘::’:

    and the original just overrides the last item without removing it?

    Yes.
    With your code you can use append() instead of groupList.last() = last; to get same behaviour.

  • @jsulm , but I’m not sure thats what the original was trying to do either. I think the original code would just update the last item.

  • @SPlatten said in error C2589: ‘(‘ : illegal token on right side of ‘::’:

    I think the original code would just update the last item

    Yes, it updates the last element. Your code now removes the last element and updates the one before last (the new last element). So, to get same behaviour using takeLast() you have to append the element which takeLast REMOVES from the list:

    [A, B, C]
    after takeLast()
    [A, B]
    after append()
    [A, B, C*]
    C* is the updated C
    
  • @jsulm , I think you missed one of my replies where I showed a replacement, changing the takeLast and replacing with just last.

  • @SPlatten The one using last() looks fine. Somehow overlooked it :-)

  • @SPlatten said in error C2589: ‘(‘ : illegal token on right side of ‘::’:

    thank you, and the original just overrides the last item without removing it?

    Yes, that is the point:

    • QList::takeLast() will return last element from QList and remove it from the list
    • QList::last() will only return a reference to last element from QList and not change list size.
  • @KroMignon, still no idea why the compiler was complaining about the original?

    groupList.back() = std::max(groupList.back(), sample);
    
  • @SPlatten said in error C2589: ‘(‘ : illegal token on right side of ‘::’:

    still no idea why the compiler was complaining about the original?

    I guess sampleand groupList.back() do not have same type and std::max() template will not be able to match them.
    Perhaps using QList::constLast()?

    // I prefere using Last() which is more clear as back()
    groupList.last() = std::max(groupList.constLast(), sample);
    

Developing on Windows 10 Pro, Visual Studio 2017 Community, C++.

Botan Version 2.9.

I’ve built a simple application to understand version 2.x.

My build goes well and the application works when everything associated with Botan is in the main module.

If I add a static lib with nothing more than the following in it’s source:

For some reason I can’t display the includes with the quotes and angle brackets:

#include stdafx.h
#include Windows.h
#include iostream
#include string
#include vector
#include botansymkey.h

two errors are generated when building that simple stub of a static library:

…botan-2botansecmem.h(86): error C2589: ‘(‘: illegal token on right side of ‘::’
…botan-2botansecmem.h(100): error C2589: ‘(‘: illegal token on right side of ‘::’

In the Librarian section of the static library’s property pages Additional Dependencies specifies botan.lib and Additional Library Directories points to the directory that contains botan.lib.

These are copy and pasted from the corresponding entries in the main modules for linker properties.

These errors relate to the following lines in secmem.h:

template<typename T, typename Alloc>
size_t buffer_insert(std::vector<T, Alloc>& buf,
size_t buf_offset,
const T input[],
size_t input_length)
{
BOTAN_ASSERT_NOMSG(buf_offset <= buf.size());
const size_t to_copy = std::min(input_length, buf.size() — buf_offset); <==========
if(to_copy > 0)
{
copy_mem(&buf[buf_offset], input, to_copy);
}
return to_copy;
}

template<typename T, typename Alloc, typename Alloc2>
size_t buffer_insert(std::vector<T, Alloc>& buf,
size_t buf_offset,
const std::vector<T, Alloc2>& input)
{
BOTAN_ASSERT_NOMSG(buf_offset <= buf.size());
const size_t to_copy = std::min(input.size(), buf.size() — buf_offset); <==========
if(to_copy > 0)
{
copy_mem(&buf[buf_offset], input.data(), to_copy);
}
return to_copy;
}

What am I forgetting?

Thanks
Larry

  • Remove From My Forums
  • Question

  • I am getting the above mentioned error.Can anyone help me out?

    The code is

    #define _STD_USING

    #else
     #include <stdint.h>
    #endif

     #if _GLOBAL_USING && !defined(RC_INVOKED)
    _STD_BEGIN
        using _CSTD int8_t; using _CSTD int16_t;
        using _CSTD int32_t; using _CSTD int64_t;
        using _CSTD uint8_t; using _CSTD uint16_t;
        using _CSTD uint32_t; using _CSTD uint64_t;

        using _CSTD int_least8_t; using _CSTD int_least16_t;
        using _CSTD int_least32_t;  using _CSTD int_least64_t;
        using _CSTD uint_least8_t; using _CSTD uint_least16_t;
        using _CSTD uint_least32_t; using _CSTD uint_least64_t;

        using _CSTD int_fast8_t; using _CSTD int_fast16_t;
        using _CSTD int_fast32_t;  using _CSTD int_fast64_t;
        using _CSTD uint_fast8_t; using _CSTD uint_fast16_t;
        using _CSTD uint_fast32_t; using _CSTD uint_fast64_t;

        using _CSTD intmax_t; using _CSTD intptr_t;
        using _CSTD uintmax_t; using _CSTD uintptr_t;

         #if _HAS_TR1_DECLARATIONS
            namespace tr1 {
        using _CSTD int8_t; using _CSTD int16_t;
        using _CSTD int32_t; using _CSTD int64_t;
        using _CSTD uint8_t; using _CSTD uint16_t;
        using _CSTD uint32_t; using _CSTD uint64_t;

        using _CSTD int_least8_t; using _CSTD int_least16_t;
        using _CSTD int_least32_t;  using _CSTD int_least64_t;
        using _CSTD uint_least8_t; using _CSTD uint_least16_t;
        using _CSTD uint_least32_t; using _CSTD uint_least64_t;

        using _CSTD int_fast8_t; using _CSTD int_fast16_t;
        using _CSTD int_fast32_t;  using _CSTD int_fast64_t;
        using _CSTD uint_fast8_t; using _CSTD uint_fast16_t;
        using _CSTD uint_fast32_t; using _CSTD uint_fast64_t;

        using _CSTD intmax_t; using _CSTD intptr_t;
        using _CSTD uintmax_t; using _CSTD uintptr_t;
            }   

         #endif
    _STD_END
     #endif

    #endif


    S Pardhu Pavan

Простейший кусок кода (файл minmax.cpp):

#include <algorithm>
int main() {
  int a = std::min(10, 20);
  return 0;
}

Все тривиально и отлично компилируется и в Visual Studio, и в CodeGear/Borland Studio, и Cygwin. Но допустим потребовались какие-то функции из Windows API, и вы подключили файл windows.h:

Теперь компиляция в Visual Studio (я проверял в 2005 и 2008) будет падать со следующей ошибкой:

minmax.cpp
minmax.cpp(4) : error C2589: '(' : illegal token on right side of '::'
minmax.cpp(4) : error C2059: syntax error : '::'

Постановка #include <windows.h> до #include <algorithm> проблемы не решает.

Очевидно, проблема в том, что кто-то переопределил значение слова min. Запустим препроцессор и проверим догадку:

cl /P minmax.cpp

И что мы видим? А видим мы следующее (фрагмент файла minmap.i):

#line 7 "minmax.cpp"
int main() {
  int a = std::(((10) < (20)) ? (10) : (20));
  return 0;
}

Естественно, это каша с точки зрения синтаксиса, и компилятор ругается совершенно законно.
Покопавшись в заголовочных файлах Windows SDK, в файле WinDef.h, который косвенно подключается через windows.h, я нашел корень зла:

#ifndef NOMINMAX

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

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

#endif  /* NOMINMAX */

Вот теперь ясно, что делать — надо определить макрос NOMINMAX, тем самым заблокировать определение min и max:

#define NOMINMAX
#include <algorithm>
#include <windows.h>
int main() {
  int a = std::min(10, 20);
  return 0;
}

Забавно, что в Cygwin и CodeGear/Borland исходный пример компилируется без проблем. В борландовой версии windows.h я нашел вот такой фрагмент:

#if defined(__BORLANDC__)
...
#    if defined(__cplusplus)
#       define NOMINMAX              /* for WINDEF.H */
...
#    endif
...
#endif /* __BORLANDC__ */

Эдак они заранее оградились от проблемы, принудительно запретив проблемные макросы.

Вывод: Порой промежуточные результаты работы препроцессора являются крайне полезной информацией.

На всякий случай напомню, как его запускать для перечисленных мной компиляторов:

Visual Studio:

cl.exe /P имя_исходника.cpp

Borland/CodeGear Studio:

cpp32.exe имя_исходника.cpp

Cygwin:

cpp.exe имя_исходника.cpp

Прочие флаги командной строки должны повторять флаги при обычной компиляции. Для препроцессора важны определения макросов (обычно это флаги -D и -U) и пути для поиска включаемых файлов (обычно это флаг -I).

Другие посты по теме:

  • Как обойтить без макроса NOMINMAX

Понравилась статья? Поделить с друзьями:
  • Error c2471 cannot update program database
  • Error c2466 невозможно выделить память для массива постоянного нулевого размера
  • Error c2447 отсутствует заголовок функции возможно используется формальный список старого типа
  • Error c2447 missing function header old style formal list
  • Error c2443 конфликт размеров операндов