为什么C ++不能将模板参数解压缩到默认构造函数中?

时间:2018-04-25 15:56:52

标签: c++ templates variadic-templates

这是

#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; ^ ~~~~~~

0 个答案:

没有答案