问题
I have a rather complicate singleton template starting with
template <class T>
class Singleton {
public:
static T& GetInstance(){
static T instance;
return instance;
}
private:
Singleton() {}
~Singleton() = default;
};
and then
class Class2;
template <class T>
class Class1{
void sayHi();
};
using Class1Singleton= Singleton<Class1<Class2>>;
So you can see I have a singleton of Class1 (that is also template based so I use Class2 for that).
Then in another part of the code I have
Class1Singleton & anObject= Class1Singleton::GetInstance();
When I try to build this I get this error
error: invalid initialization of reference of type
‘Class1Singleton& {aka Singleton<Class1<Class2> >&}’
from expression of type ‘Class1<Class2>’
Class1Singleton::GetInstance();
^
Why is the Singleton being ignored??
回答1:
You have:
template <class T>
class Singleton {
public:
static T& GetInstance();
};
Singleton<T>& anObject = Singleton<T>::GetInstance();
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ type is T&
//^^^^^^^^^^^ type is Singleton<T>&
The types don't match up. You are trying to initialize a reference to Singleton<T>
with a reference to T
.
You ask in the comments, "how can I return a singleton?". If you really want to return a Singleton<T>
you can:
template <class T>
class Singleton {
public:
static Singleton<T>& GetInstance() {
// ^^^^^^^^^^^^^ return the type you want to return
static Singleton<T> instance;
return instance;
}
private:
Singleton() = default;
~Singleton() = default;
};
来源:https://stackoverflow.com/questions/65070832/invalid-initialization-of-type-using-class-templates