gpt4 book ai didi

c++ - 使用类型特征时如何排列文件?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:18:01 24 4
gpt4 key购买 nike

我第一次尝试在 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 相关的模板化内容简化了输出,例如 std::allocatorstd::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, &parameter);
}
}

// 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:: 的出现以使代码更具可读性。)

我需要如何组织我的代码文件并包含它才能正常工作?

最佳答案

不要在 header 中定义静态成员。您将在 #include header 的每个 TU 中引入定义。

改为在 一个 TU 中定义它们;最简单的方法是在 .cpp 文件中。

关于c++ - 使用类型特征时如何排列文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19763182/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com