我知道有一个initailzer技巧可以强制构建一个全局对象,无论它在何处使用。这用于std :: cout我相信。
#ifndef GUARD_H
#define GUARD_H
class Magical
{
// default constructor and such...
};
class Init
{
public:
Init();
};
extern Magical& magic;
namespace
{
Init __magical_initializer; // works as this object is constructed in every source file it is included in
}
#endif
的src:
#include "magical.h"
#include <new>
static int count; // believe there is a spec somewhere which states global integers are initialized with zero
static alignas(Magical) char buffer[sizeof(Magical)];
Magical& magic = *reinterpret_cast<Magical*>(buffer);
Init::Init()
{
if(!count++)
{
new(buffer) Magical;
}
}
我想知道是否有与此相当的模板,因此我的代码看起来像这样:
template<typename T>
class Base
{
static Magical<T> __private; // need this constructor to be called.
};
// usage:
class SomeClass : public Base<SomeClass>
{
};
答案 0 :(得分:0)
无法解决此问题,因为源文件中不存在模板。