saz*_*azr 0 c++ templates static-cast
我有一个通用的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.
};
Run Code Online (Sandbox Code Playgroud)
有可能这样投吗?我不想instance()返回指针,我更喜欢引用.或者是一个weak_ptr?任何想法如何投这个?
您正在寻找的是使用间接运算符取消引用指针*.你也想要
return static_cast<DERIVED&>(*_instance);
// ^^^^^
Run Code Online (Sandbox Code Playgroud)
要么
return *static_cast<DERIVED*>(_instance);
// ^^^^^
Run Code Online (Sandbox Code Playgroud)
或者干脆:
return *_instance;
// ^^^^^
Run Code Online (Sandbox Code Playgroud)
因为_instance 已经有类型Derived *,上面的两个演员都是无操作.