【发布时间】:2014-10-28 10:11:59
【问题描述】:
我正在尝试编译如下所示的 C++ 代码,但出现错误提示,
在 src/LM.h:3:0 包含的文件中, 来自 src/LM.cpp:1: src/common.h:30:13:错误:“哈希”已在此范围内声明 使用 tr1::hash;
这是我用来编译以下文件的命令。
g++ -std=c++11 -Wall src/Foo.cpp
Foo.cpp
#include "Foo.h"
...
Foo.h
#ifndef FOO_H
#define FOO_H
#include "common.h"
//more code here
#endif
common.h
#ifndef _COMMON_H_
#define _COMMON_H_
#include <iostream>
#include <fstream>
#include <cmath>
#include <cassert>
#include <cstdlib>
#include <utility>
#include <vector>
#include <string>
#include <array>
#include <algorithm>
#include <set>
#include <tr1/unordered_map>
#include <tr1/functional>
namespace std {
using tr1::unordered_map;
using tr1::hash;
} // namespace std
using namespace std;
//more code here
#endif
我希望源代码使用 std::tr1::unordered_map 和 std::tr1::hash 而不是 std::unordered_map 和 std::hash(实际上我正在对使用 std 的分布式文件进行一些修改::tr1::unordered_map 和 std::tr1::hash)。
我的代码可能有什么问题?
更新: https://github.com/clab/fast_align/blob/master/src/port.h 似乎和我做的一样。但是,这编译没有任何问题......有什么想法吗?
【问题讨论】:
-
出于兴趣,为什么要使用
std::tr1::hash而不是std::hash? -
port.h编译是因为它不包含<utility>,它声明了真正的std::hash。 -
我正在修改的源代码使用的是 std::tr1::hash 所以我只是关注它,因为我不熟悉这些东西。有什么大的不同吗?
-
这就是我们不做
using namespace std;的原因。如果您尝试修改使用tr1::hash的代码,那么执行 grep/search-and-replace 比您尝试执行的操作更好,也更简单。 -
@HitoshiOtsuki:一旦你在程序中引入了一个名字,你就不能把它扔掉并用别的东西代替,不。而且,你真的不应该像这样破坏你的标准库实现。使用提供的
std::hash。