【发布时间】:2013-05-09 14:06:47
【问题描述】:
在下面的代码中,行
const char * const * eNames (names+cntNames);
在 Visual Studio 2008 中导致 C2061 错误:
语法错误:标识符“标识符”- 编译器发现了一个非预期的标识符。 确保在使用之前声明了标识符。 初始化器可以用括号括起来。 为避免此问题,请将声明符括在括号中或使其成为 typedef。 当编译器将表达式检测为类时,也可能导致此错误 模板参数;使用 typename 告诉编译器它是一个类型。
如果我改成
const char * const * eNames = names+cntNames;
它不会抱怨。这是编译器错误吗?如果不是,为什么投诉?
我的关于框显示:版本 9.0.30729.1 SP
我的 GCC 同事没有看到此错误。
#include <string>
#include <algorithm>
#include <functional>
#include <iostream>
namespace ns1 {
struct str_eq_to
{
str_eq_to(const std::string& s) : s_(s) {}
bool operator()(const char* x) const { return s_.compare(x)==0; }
const std::string& s_;
};
static bool getNameIndex(const char * const * names, size_t cntNames, const std::string& nm, int &result)
{
const char * const * eNames (names+cntNames); //VS2008 error C2061: syntax error : identifier 'names'
const char * const * p = std::find_if(names, eNames, str_eq_to(nm));
if(p==eNames) return false;
result = p-names;
return true;
}
} //namespace ns1
int main() {
const char * const names[] = {"Apple", "Orange","Plum"};
std::string str = "Plum";
int res;
ns1::getNameIndex(names, 3, str, res);
std::cout << str << " is at index " << res << std::endl;
return 0;
}
【问题讨论】:
-
VS 2008 已经有 5 年历史了,在编译器年代已经很老了,而且(显然)从那时起就没有跟上 C++ 的发展。我建议您下载 VS 2012 Express(零成本,需要注册)并在那里试用。如果它有效,你可以假设 VS 2008 是错误的。
-
这看起来像是一个最令人头疼的解析相关问题。尝试第二组括号:
const char * const * eNames ((names+cntNames)); -
@MarkB - VS2008 然后不喜欢双括号并为每个括号获取 C2059。
-
@Zack 我刚刚尝试在 VS 2012 Ultimate 中编译,我遇到了同样的错误。
-
避免让语句看起来像函数原型,编译器会很高兴。
标签: c++ most-vexing-parse