我的完整代码太长,但这里有一个片段可以反映我的问题的本质:
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 http://www.parashift.com/c++-faq-lite/misc-technical-issues.html)我读到:
Whenever you use a class as a template parameter, the declaration of that class must be complete and not simply forward declared.
所以我被困住了。之后我无法专门化模板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
在给出的答案中速度评论 http://www.velocityreviews.com/forums/t672186-namespace-within-class.html,有人声称命名空间不能在类中定义。所以我还是被困住了。