I want to make a singleton class template, but i found it created two class out, which violate the singleton's purpose.
here is my code:
single.hpp (template class for singleton)
#pragma once
template<typename T>
class Singleton {
protected:
Singleton() = default;
Singleton(const Singleton&) = delete;
Singleton(const Singleton&&) = delete;
virtual ~Singleton() = default;
public:
void operator = (const T&) = delete;
template <typename ... Args>
static T& GetInst(const Args&... args) {
static T inst(args...);
return inst;
}
};
singleton class a.hpp:
#include "single.hpp"
#include <string>
#include <stdio.h>
class A : public Singleton<A> {
public:
A(const std::string& name) {
printf("construct a new A with name %s\n", name.c_str());
}
~A() {
printf("deconstuctor called\n");
}
}
main.cpp:
#include "a.hpp"
int main() {
A a = A::GetInst("a");
A b = A::GetInst("b");
}
the output of main is:
construct a new A with name a
construct a new B with name b
deconstructor called
deconstructor called
is there anything wrong with my code?
if i dont use variadic template function, can this work? if so, does this mean we cant pass parameters to a singleton class's constructor?
Aucun commentaire:
Enregistrer un commentaire