【问题标题】:Template inheritance with static properties (Service Locator Pattern)具有静态属性的模板继承(服务定位器模式)
【发布时间】:2012-12-19 12:16:13
【问题描述】:

我一直在尝试使用模板化基类并从它继承来实现服务定位器模式:

    // Header File
    namespace one {
    template <class I, class N>
    class Locator {
    public:
        static void initialize() {
            service = &nullService;
        }
        static void provide(I* newService) {
            if (newService == 0) {
                initialize();
            } else {
                service = newService;

        }
        static I& get() { return *service; }
        virtual ~Locator() {
            if (service != &nullService) {
                delete service;
            }
    private:
        Locator();
        static I* service;
        static N nullService;
    };
    }

    // Source File
    #include "Locator.hpp"

    namespace one {
    template<class I, class N>
    I* Locator<I, N>::service;

    template<class I, class N>
    N Locator<I, N>::nullService;
    }

class I是实例类,class N是空服务类。 对于派生类:

    // Header File
    namespace two {
    class ExampleLocator : public one::Locator<Service, NullService> {}
    }

    // Source File
    namespace one {
    template class Locator<Service, NullService>;
    }

当我尝试使用这个实现时,

    int main(int argc, char const *argv[]) {
        two::ExampleLocator::initialize();
        two::ExampleLocator::get().doSomething();
    }

gcc 编译失败,出现以下错误:

  • 对 one::Locator::initialize() 的未定义引用
  • 在函数 one::Locator::get() 中:未定义对 one::Locator::service 的引用

我做错了什么?

注意:我可以通过在派生类的 cpp 中重新声明 Locator 的静态属性来编译项目:

    // Alternative Derived class Source file
    namespace one {
    template<class I, class N>
    I* Locator<I, N>::service;

    template<class I, class N>
    N Locator<I, N>::nullService;

    template class Locator<Service, NullService>;
    }

注意 2:Derived 类与 Locator 类位于不同的命名空间中。

【问题讨论】:

  • Pubby 已经回答了你的问题;我只想补充一点,你在析构函数中也有一个错误。如果它不等于&amp;nullService,您应该只使用delete service

标签: c++ templates inheritance properties static


【解决方案1】:

模板定义必须在所有使用它们的翻译单元中可见。将 .cpp 文件中的代码移动到 .hpp 文件中。

见:Why can templates only be implemented in the header file?

【讨论】:

  • @JuanPablo 如果是同样的错误,那么更新问题。否则发布一个新的。
猜你喜欢
  • 2012-10-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-17
  • 2011-04-16
  • 2019-08-15
  • 1970-01-01
相关资源
最近更新 更多