Jua*_*blo 3 c++ inheritance static templates properties
我一直在尝试使用模板化基类实现Service Locator模式并从中继承:
// 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;
}
Run Code Online (Sandbox Code Playgroud)
class I是实例类,N类是null服务类.对于派生类:
// Header File
namespace two {
class ExampleLocator : public one::Locator<Service, NullService> {}
}
// Source File
namespace one {
template class Locator<Service, NullService>;
}
Run Code Online (Sandbox Code Playgroud)
当我尝试使用这个实现时,
int main(int argc, char const *argv[]) {
two::ExampleLocator::initialize();
two::ExampleLocator::get().doSomething();
}
Run Code Online (Sandbox Code Playgroud)
gcc无法使用以下错误进行编译:
我究竟做错了什么?
注意:我可以通过在Derived类的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>;
}
Run Code Online (Sandbox Code Playgroud)
注意2:Derived类与Locator类位于不同的命名空间中.