【问题标题】:Very Confused on Template INL File对模板 INL 文件非常困惑
【发布时间】:2015-08-11 18:51:00
【问题描述】:

好的,我以为我已经找到了模板类的实现文件,但显然没有……我在 VS 2013 C++ 解决方案中有以下文件:

Main.cpp

#include "StateManager.h"
#include "State.h"

enum class Derp {
    Herp,
    Lerp,
    Sherp,
};

int main() {
    Game2D::State<Derp>::Context context(5);
    Game2D::StateManager<Derp> mgr(context);

    return 0;
}

StateManager.h

#pragma once

#include "State.h"

namespace Game2D {

    template<typename Id>
    class StateManager {
    private:
        typename State<Id>::Context _context;

    public:
        explicit StateManager(typename State<Id>::Context context);
    };

#include "StateManager.inl"

}

StateManager.inl

template<typename Id>
StateManager<Id>::StateManager(typename State<Id>::Context context) :
    _context(context)
{ }

状态.h

#pragma once

namespace Game2D {

    template<typename Id>
    class StateManager;

    template<typename Id>
    class State {
    public:
        struct Context {
            Context(int);
            int data;
        };

    private:
        StateManager<Id>* _manager;
        Context _context;

    public:
        State(StateManager<Id>&, Context);
        virtual ~State();

    };

#include "State.inl"

}

State.inl

template<typename Id>
State<Id>::Context::Context(int data) {
    this->data = data;
}

template<typename Id>
State<Id>::State(StateManager<Id>& manager, Context context) :
    _manager(&manager),
    _context(context)
{ }
template<typename Id>
State<Id>::~State() { }

构建此项目会产生以下错误:

错误 10 错误 C1903:无法从先前的错误中恢复;停止编译 state.inl 9 1

错误 9 错误 C2065:“上下文”:未声明的标识符 state.inl 8 1

错误 7 错误 C2065:“经理”:未声明的标识符 state.inl 7 1

错误 8 错误 C4430:缺少类型说明符 - 假定为 int。注意:C++ 不支持 default-int state.inl 7 1

错误 6 错误 C2039: 'State' : is not a member of '`global namespace'' state.inl 6 1

错误 1 ​​错误 C2143:语法错误:缺少 ';'在'之前

错误 2 错误 C2988:无法识别的模板声明/定义 state.inl 2 1

错误 3 错误 C2059:语法错误:'

错误 4 错误 C3083: 'Context': '::' 左侧的符号必须是 state.inl 2 1 类型

错误 5 错误 C2039: 'Context' : is not a member of '`global namespace'' state.inl 2 1

任何有关如何修复这些错误的帮助将不胜感激!

【问题讨论】:

  • 尝试提交MCVE。如果每个函数都产生这些错误,则只保留一个函数。删除不必要的成员声明并包含指令。
  • 它失败了 M、C 和 V 部分。 M:它有很多函数定义,一个就够了。 C: 没有 State.h V: 我不能拿你的例子来编译它并得到你得到的所有相同的错误。如果这确实是您的源代码,请注意它有很多右括号被注释掉了。
  • 好的,我更新了我原来的帖子
  • 无法重现错误here。确保您发布的文件是您编译的文件。
  • 那么,哪些行会触发这些错误?哪个是第一个错误?为什么您引用的第一条错误消息提到“以前的错误”?在这种情况下,哪些错误是“以前的”?

标签: c++ header-files class-template


【解决方案1】:

一个大胆的猜测是您将.inl 文件作为独立翻译单元添加到您的项目中,而编译器试图将它们编译为独立翻译单元。

这些文件作为独立的翻译单元毫无意义,它们不会被编译。这些是包含文件(又名头文件)。它们应该被项目视为头文件。它们不应该直接编译。

【讨论】:

  • 那么我如何向编译器指定它们不是翻译单元?
  • @Rabadash8820:这取决于你的编译器。例如,在 Visual Studio 中,您不要将它们添加到 Source Files 类别下。如果要将它们添加到项目中,请将它们添加到 Header Files 类别下。或者,您可以简单地将它们从构建项目设置中排除。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-14
  • 1970-01-01
  • 2012-08-13
相关资源
最近更新 更多