非常困惑的模板INL文件

Very Confused on Template INL File

本文关键字:INL 文件 非常      更新时间:2023-10-16

好吧,我以为我有模板类的实现文件弄清楚了,但显然不是…我在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)
{ }

State.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:无法从之前的错误中恢复;停止编译状态。1

错误9错误C2065: 'context':未声明的标识符状态。1

错误7 C2065: 'manager':未声明的标识符状态。1

错误8错误C4430:缺少类型说明符-假定为int。注意:c++不支持default-int状态。1

错误6错误C2039:"状态":不是"全局命名空间"状态的成员。1

错误1 C2143:语法错误:在"<"状态之前缺少";"。Inl 2 1

错误2错误C2988:无法识别模板声明/定义状态。Inl 2 1

错误3错误C2059:语法错误:'<'状态。Inl 2 1

错误4错误C3083: 'Context': '::'左边的符号必须是类型状态。Inl 2 1

错误5错误C2039: 'Context':不是' global namespace'状态的成员。Inl 2 1

任何关于如何修复这些错误的帮助将非常感激!

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

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