我第一次尝试在 C++ 中实现特征,但我遇到了多个已定义符号的链接错误。
error LNK2005: "public: static class std::unordered_map<std::string, std::string> const ManagerTrait<struct Specialized>::Fields"
error LNK2005: "public: static class std::unordered_map<std::string, std::string> const ManagerTrait<struct Specialized>::Fields"
error LNK2005: "public: static class std::unordered_map<std::string, std::string> const ManagerTrait<struct Specialized>::Fields"
error LNK2005: "public: static class std::unordered_map<std::string, std::string> const ManagerTrait<struct Specialized>::Fields"
error LNK2005: "public: static class std::unordered_map<std::string, std::string> const ManagerTrait<struct Specialized>::Fields"
error LNK2005: "public: static class std::unordered_map<std::string, std::string> const ManagerTrait<struct Specialized>::Fields"
error LNK1169: one or more multiply defined symbols found
(我通过删除与std::unordered_map
like std::allocator
、等相关的模板化内容来简化输出std::hash
。)
基本上,有一个Manager
使用特征的类、一个默认特征类和一些专门的特征。但是所有特殊的特征都需要访问类的嵌套类型Manager
。
经理.h
#pragma once
class Manager
{
class Parameter
{
// ...
};
template <typename T>
void Usage(T* Instance)
{
typedef ManagerTrait<T> Trait;
// access unordered map
for(auto i : Trait::Fields) { /* ... */ }
// access function
Parameter parameter;
Trait::Function(Instance, ¶meter);
}
}
// would like to move that in dedicated manager/trait.h
template <typename T>
struct ManagerTrait;
专门的.h
#pragma once
#include "manager.h"
class Specialized
{
// ...
};
// would like to move in a dedicated specialized/trait.h
template <>
struct ManagerTrait<Specialized>
{
// define unordered map
static const unordered_map<string, string> Fields;
// define function
static void Function(Specialized *Instance, Manager::Parameter *Parameter)
{
// ...
}
};
// populate unordered map
const unordered_map<string, string> ManagerTrait<Specialized>::Fields = []{
unordered_map<string, string> fields;
// insert some elements
// ...
return fields;
}();
(我删除了命名空间的std::
出现以使代码更具可读性。)
我需要如何组织我的代码文件和包含以使其工作?