Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get an "illegal token" compile-time error with this piece of C++ code?

In my application (compiled under Visual C++ 2010), I have code like this in a header file:

// example.h
#pragma once

#include <limits>

namespace myspace
{

// A generic equality test
template<typename T> inline bool equal(
    const T &v1, 
    const T &v2, 
    const T &eps = std::numeric_limits<T>::epsilon())
{
    return (v1 == v2);
}

// Template specialization for floating-point numbers
template<> bool equal<float>(
    const float &v1, 
    const float &v2, 
    const float &eps);

// A generic equality test for finite-precision real number representations (with epsilon)
template<typename T> inline bool realEqual(
    const T &p, 
    const T &q, 
    const T &eps = std::numeric_limits<T>::epsilon())
{
    return (fabs(p - q) < eps);
}

} // namespace myspace

...and some code in a .cpp file:

// example.cpp
#include "example.h"

using namespace std;
using namespace myspace;

// equal-macro specialization that calls the appropriate equality test function for real numbers
template<> bool myspace::equal<float>(
    const float &v1, 
    const float &v2, 
    const float &eps)
{
    return (realEqual(v1, v2, eps));
}

int _tmain(int argc, _TCHAR* argv[])
{
    float a,b;
    bool x = realEqual(a,b); // OK
    bool x = equal(a,b); // compile error
    return 0;
}

This fails to compile, giving me:

------ Build started: Project: test, Configuration: Debug Win32 ------
test.cpp
c:\users\ninja\documents\visual studio 2010\projects\test\test\test.h(10): error C2589: '::' : illegal token on right side of '::'
c:\users\ninja\documents\visual studio 2010\projects\test\test\test.h(10): error C2059: syntax error : '::'
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

The offending line is the one with the definition of the "eps" parameter's default value for the equal() function.

A google search revealed people've had similar "illegal token" errors with other functions from numeric_limits, namely min() and max(), but these were due to some #define present in Windows-specific c++ standard library header files, which defined "min" and "max" for some legacy reasons. No mention about epsilon(), and I'm absolutely stumped about why I'm getting an error here. Anyway, changing the function name from "equal" to something like "smartEqual" still gives the same error, so the name is obviously not the issue. What is?

Thanks!

like image 231
neuviemeporte Avatar asked Apr 27 '12 00:04

neuviemeporte


1 Answers

It looks like it's caused by this bug in Visual Studio:

https://connect.microsoft.com/VisualStudio/feedback/details/583081/

See also here:

template function specialization default argument

like image 146
Stuart Golodetz Avatar answered Nov 15 '22 14:11

Stuart Golodetz