2014-10-28 30 views
1

我試圖編譯如下所示的C++代碼,但我得到一個錯誤的說法,'hash'已在此範圍內使用tr1 :: hash聲明;

In file included from src/LM.h:3:0, from src/LM.cpp:1: src/common.h:30:13: error: ‘hash’ is already declared in this scope using 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(A ctually我正在做一些修改分佈式文件,它使用std :: tr1 :: unordered_map和std :: tr1 :: hash)。

我的代碼可能有什麼問題?

UPD: https://github.com/clab/fast_align/blob/master/src/port.h似乎和我一樣。但是,這個編譯沒有任何問題...有任何想法?

+1

出於興趣你爲什麼要使用'std :: tr1 :: hash'而不是'std :: hash'? – sjdowling 2014-10-28 10:23:02

+1

'port.h'編譯是因爲它不包含'',它聲明瞭真正的'std :: hash'。 – 2014-10-28 10:25:38

+0

我修改的源代碼是使用std :: tr1 :: hash,所以我只是跟着它,因爲我不熟悉這些東西。有什麼很大的區別? – hitochan 2014-10-28 10:25:59

回答

5

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 

} 
+0

謝謝:)如果std :: hash與std :: tr1 :: hash差別不大,那麼我只會使用std :: hash。 – hitochan 2014-10-28 10:34:16

+0

'std :: hash'和'std :: tr1 :: hash'在C++ 11實現中應該是相同的東西;如果他們不是,我會非常驚訝! – LThode 2014-10-28 17:09:27

+0

@LThode如果是這樣,爲什麼有兩個相同的實現? – hitochan 2014-10-29 01:42:55