我的完整代码太长了,但这里有一个代码片段可以反映出我的问题的实质:
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的一个回答中,有人声称无法在类内定义命名空间。所以我还是卡住了。