【发布时间】:2015-05-30 18:10:00
【问题描述】:
我在尝试初始化静态类模板的静态成员时遇到问题。
基本上,我认为这种方法对以下方面有用: 我有很多对象,当然它们都是相同的 Base 类型,但它们具有不同的对象类型。我只是想操作这些对象,这就是我决定使用静态模板的原因,因为这些对象可以包含很多不同的类型。
但是,对于日志记录和选项传递,我想将相应的成员添加到模板中,而不必为每个派生静态类编写初始化程序。
请注意,以下代码不实际工作,因为涉及一些 SDK。 我只是在寻求正确的方法,而不是正确的代码。
提前致谢。 :)
模板.h:
#ifndef _TEMPLATE_H
#define _TEMPLATE_H
#include "stats.h"
template<class T>
class TemplateObj
{
public:
static void SetParameters(const Options& options)
{
T::_options = options; // Is this even possible?
T::Init();
T::DoStuff(_options);
}
protected:
static void Message() { stats.Print("Message from Template static method"); }
static Stats& TemplateObj<T>::stats = Stats::GetInstance(); // This will not work as this is a non-trivial initializer, how to do it correctly? Stats::GetInstance() retrieves a singleton instance
static Options& TemplateObj<T>::_options; // Possible?
};
#endif
派生的.h:
#ifndef _DERIVED_H
#define _DERIVED_H
#include "template.h"
class Derived :TemplateObj < Derived >
{
public:
static void Init();
static void DoStuff(Options& options)
};
#endif
派生的.cpp:
#include "derived.h"
void Derived::Init()
{
// Init stuff here
TemplateObj::Message(); // Call static method from template directly
}
void Derived::DoStuff(Options& options)
{
// Do something with options
stats.Print("Message from derived static method."); // Access to "stats" here. "stats" should be declared and initialized inside the template.
options.Load(); // Example
}
main.h
#include "derived.h"
main()
{
TemplateObj<Derived>::SetParameters(new Options);
}
【问题讨论】:
-
就像普通的非模板类一样,你需要在类中声明一个静态成员,然后在类外定义它。 Like this
-
@IgorTandetnik:就是这样!我对模板很陌生,所以我可能忽略了它。非常感谢! :)
标签: templates c++11 visual-c++ static msvc12