Invalid initialization of type using class templates

只愿长相守 提交于 2021-01-29 05:32:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!