引用指针是非法的

时间:2018-02-28 12:25:43

标签: c++ templates reference c++14 pass-by-reference

我最近一直在进行模板元编程,只是意识到模板调试有多么困难。例如,当我尝试编译以下代码时,我收到“指向引用的指针是非法的”错误:

index.html

错误的原因是#include <vector> #include <tuple> //Empty Entity Class class Entity { }; #define COMPONENTS X(Entity) #define COMPONENTSLIST X(Entity) #define X(ARG) std::vector<ARG> using ComponentTuple = std::tuple<COMPONENTSLIST>; #undef X //EntityManager stuff class EntityManager { static ComponentTuple components; public: template<class T> static auto& Components(); template<class T> static void AddComponent(Entity&, T&&); }; template<class T> auto& EntityManager::Components() { return std::get<std::vector<T>>(components); } template<class T> void EntityManager::AddComponent(Entity& e, T&& c) { auto& comp = Components<T>();; comp.push_back(c); } #define X(ARG) std::vector<ARG> std::tuple<COMPONENTSLIST> EntityManager::components; #undef X //ContentManager Stuff class ContentManager { bool LoadComponent(std::string data, Entity& entity); template <class T> static void LoadComponent(std::string data, Entity& entity); }; template <class T> void ContentManager::LoadComponent(std::string data, Entity& entity) { T component{}; EntityManager::AddComponent(entity, component); } bool ContentManager::LoadComponent(std::string data, Entity& entity) { LoadComponent<Entity>(data, entity); } 中的行EntityManager::AddComponent(entity, component);(考虑到LoadComponent的错误点,这一点并不容易理解。)

我遇到的问题是我从未请求指针,据我所知,所以这个错误对我来说似乎很奇怪。

此时,我们将非常感谢任何帮助(与错误甚至是未来模板调试的提示有关)。提前谢谢。

1 个答案:

答案 0 :(得分:0)

AddComponent的语法更改为:

static void AddComponent(Entity&, T);

static void AddComponent(Entity&, const T&);

并且您的代码至少使用gcc进行编译。因此,这不一定与您的模板有关,而是以push_back处理右值引用的方式。

相关问题