我有一个通用的Singleton类,将用于许多Singleton类。从指针转换为引用时,泛型类给出了编译错误。


  错误3错误C2440:“ static_cast”:无法从“ IApp *”转换为“ IApp&”


下面是通用类,instance()函数中发生编译器错误。

template<typename DERIVED>
class Singleton
{
public:

    static DERIVED& instance()
    {
        if (!_instance) {
            _instance = new DERIVED;
            std::atexit(_singleton_deleter); // Destruction of instance registered at runtime exit (No leak).
        }

        return static_cast<DERIVED&>(_instance);
    }

protected:

    Singleton() {}
    virtual ~Singleton() {}

private:

    static DERIVED* _instance;

    static void _singleton_deleter() { delete _instance; } //Function that manages the destruction of the instance at the end of the execution.

};


有可能以这种方式进行投射吗?我不想instance()返回一个指针,我希望有一个引用。还是weak_ptr?有任何想法如何投射吗?

最佳答案

您正在寻找的是使用间接运算符*取消指针的引用。你想要

return static_cast<DERIVED&>(*_instance);
//                         ^^^^^


要么

return *static_cast<DERIVED*>(_instance);
//   ^^^^^


或者简单地:

return *_instance;
//   ^^^^^


因为_instance已经具有类型Derived *并且上面的两个强制类型转换为no-ops。

关于c++ - 从指针转换到引用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34427609/

10-11 19:32
查看更多