为什么我用这段C ++代码得到“非法令牌”编译时错误?

时间:2012-04-27 00:23:10

标签: c++ visual-studio compiler-errors numeric-limits

在我的应用程序中(在Visual C ++ 2010下编译),我在头文件中有这样的代码:

// 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

...以及.cpp文件中的一些代码:

// 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;
}

这无法编译,给我:

  

------ Build build:Project:test,Configuration:Debug Win32 ------
   TEST.CPP
  c:\ users \ ninja \ documents \ visual studio 2010 \ projects \ test \ test \ test.h(10):错误C2589:'::':'::'右侧的非法令牌
  c:\ users \ ninja \ documents \ visual studio 2010 \ projects \ test \ test \ test.h(10):错误C2059:语法错误:'::'
  ==========构建:0成功,1个失败,0个最新,0个跳过==========

违规行是定义“eps”参数的equal()函数的默认值。

谷歌搜索显示人们与numeric_limits中的其他函数有类似的“非法令牌”错误,即min()和max(),但这些是由于某些特定于Windows的c ++标准库头文件中存在#define ,由于某些遗留原因,它定义了“min”和“max”。没有提到epsilon(),我完全不知道为什么我在这里收到错误。无论如何,将函数名称从“相等”更改为类似“smartEqual”的内容仍会产生相同的错误,因此名称显然不是问题。是什么?

谢谢!

1 个答案:

答案 0 :(得分:7)