【问题标题】:‘hash’ is already declared in this scope using tr1::hash;'hash' 已经使用 tr1::hash 在此范围内声明;
【发布时间】: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 编译是因为它不包含&lt;utility&gt;,它声明了真正的std::hash
  • 我正在修改的源代码使用的是 std::tr1::hash 所以我只是关注它,因为我不熟悉这些东西。有什么大的不同吗?
  • 这就是我们不做using namespace std;的原因。如果您尝试修改使用 tr1::hash 的代码,那么执行 grep/search-and-replace 比您尝试执行的操作更好,也更简单。
  • @HitoshiOtsuki:一旦你在程序中引入了一个名字,你就不能把它扔掉并用别的东西代替,不。而且,你真的不应该像这样破坏你的标准库实现。使用提供的std::hash

标签: c++ c++11 tr1


【解决方案1】:

C++11 中已经有std::hash。你不能重新定义它。您可以为tr1::hash 使用其他名称。

可能最好的想法(如果你真的想使用 std::tr1::hash/std::tr1::unordered_map 而不是 C++11 结构)是编写你自己的命名空间,其中 using 所有结构,你想要没有 std::hash/std::unordered_map

namespace common
{

using std::tr1::hash;
using std::tr1::unordered_map;
using std::vector;
// and so on

}

【讨论】:

  • 谢谢 :) 如果 std::hash 与 std::tr1::hash 差别不大,我将只使用 std::hash。
  • std::hashstd::tr1::hash 在 C++11 实现上应该是相同的;如果他们不是,我会非常惊讶!
  • @LThode 如果是,为什么会有两个相同的实现?
  • @HitoshiOtsuki:历史。 std::tr1::hash 以 C++98/03 的技术报告 1 排在首位。当 C++11 出现时,TR1 标准库添加成为成熟的标准库类,因此 std::hash
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-20
相关资源
最近更新 更多