这是
#include <iostream>
template <typename T, typename... Args>
T* getSingleton(Args... args) {
static T instance(args...);
return &instance;
}
class MyType1 {
public:
MyType1(int val) {}
MyType1(const MyType1&) = delete;
MyType1(MyType1&&) = delete;
};
class MyType2 {
public:
MyType2() {}
MyType2(const MyType2&) = delete;
MyType2(MyType2&&) = delete;
};
int main() {
std::cout << getSingleton<MyType1>(11) << std::endl; // works
// std::cout << getSingleton<MyType2>() << std::endl; // doesn't work
return 0;
}
收到错误:
prog.cpp:实例化'T * getSingleton(Args ...)[用T = MyType2; Args = {}]':prog.cpp:24:37:从这里需要 prog.cpp:5:27:错误:使用已删除的功能 'MyType2 :: MyType2(MyType2&amp;&amp;)'静态T实例(args ...); ^ prog.cpp:19:2:注意:在这里声明MyType2(MyType2&amp;&amp;)= delete; ^ ~~~~~~