我完整的代碼太長,但這裏是一個片段,將反映我的問題的實質:實例化後模板的專業化?
class BPCFGParser {
public:
...
...
class Edge {
...
...
};
class ActiveEquivClass {
...
...
};
class PassiveEquivClass {
...
...
};
struct EqActiveEquivClass {
...
...
};
struct EqPassiveEquivClass {
...
...
};
unordered_map<ActiveEquivClass, Edge *, hash<ActiveEquivClass>, EqActiveEquivClass> discovered_active_edges;
unordered_map<PassiveEquivClass, Edge *, hash<PassiveEquivClass>, EqPassiveEquivClass> discovered_passive_edges;
};
namespace std {
template <>
class hash<BPCFGParser::ActiveEquivClass>
{
public:
size_t operator()(const BPCFGParser::ActiveEquivClass & aec) const {
}
};
template <>
class hash<BPCFGParser::PassiveEquivClass>
{
public:
size_t operator()(const BPCFGParser::PassiveEquivClass & pec) const {
}
};
}
當我編譯這段代碼,我得到以下錯誤:
In file included from BPCFGParser.cpp:3,
from experiments.cpp:2:
BPCFGParser.h:408: error: specialization of ‘std::hash<BPCFGParser::ActiveEquivClass>’ after instantiation
BPCFGParser.h:408: error: redefinition of ‘class std::hash<BPCFGParser::ActiveEquivClass>’
/usr/include/c++/4.3/tr1_impl/functional_hash.h:44: error: previous definition of ‘class std::hash<BPCFGParser::ActiveEquivClass>’
BPCFGParser.h:445: error: specialization of ‘std::hash<BPCFGParser::PassiveEquivClass>’ after instantiation
BPCFGParser.h:445: error: redefinition of ‘class std::hash<BPCFGParser::PassiveEquivClass>’
/usr/include/c++/4.3/tr1_impl/functional_hash.h:44: error: previous definition of ‘class std::hash<BPCFGParser::PassiveEquivClass>’
現在我必須爲這些類專門化std :: hash(因爲標準std :: hash定義不包括用戶定義的類型)。當我在BPCFGParser
類的定義之前移動這些模板專業化時,我會嘗試各種各樣的錯誤,並且在某處(http://www.parashift.com/c++-faq-lite/misc-technical-issues.html)我讀到:
每當您使用類作爲模板參數時,聲明該類必須完整,而不是簡單地向前聲明。
所以我卡住了。我不能專注BPCFGParser
定義後的模板,我不能在BPCFGParser
定義之前將它們專門化,我怎麼能得到這個工作?
您需要向專業化轉移到一個內部類BPCFGParser內。這樣做符合兩個要求。
非常感謝您對
hash
類的命名空間std
中定義的答案:)。它不允許我在非命名空間範圍內專門化hash
的模板。甚至以下:
template <>
class std::hash<ActiveEquivClass> {
...
沒有工作。當我附上了專業化與namespace std {}
,但是,它給出了奇怪的錯誤:
In file included from BPCFGParser.cpp:3,
from experiments.cpp:2:
BPCFGParser.h:225: error: expected unqualified-id before ‘namespace’
experiments.cpp:7: error: expected `}' at end of input
BPCFGParser.h:222: error: expected unqualified-id at end of input
在velocityreviews給出一個答案,有人聲稱,命名空間不能類中定義。所以我仍然堅持。
非常感謝您的答案,但它不起作用。請參閱下面的說明。 – 2009-12-13 01:58:59