如何将类类型作为参数传递给新操作的函数模板?

wan*_*yde 0 c++ class new-operator function-templates

我有一段 C++ 代码:

#include <iostream>
#include <string>
#include <map>

static counter = 0;

class Probe
{
private:
    int supply_;
    Probe(const Probe&);

public:
    Probe()
    {
        supply_ = 10000;
    }

    int get_supply()
    {
        return supply_;
    }

};

/********************************************************************************
template<class T> T Create(int counter, T& produced)
{
    produced[counter] = new ; // ??????????????????????????????????????
    return produced;
}
************************************************************************************/

std::map<int, Probe*> CreatInitWorkers(int counter, std::map<int, Probe*> &init_workers) 
{
    init_workers[counter] = new Probe(); 
    return init_workers;
}


int main()
{ 
    std::map<int, Probe*> workers;
    for (int i = 0; i < 12; i++)
    {
        workers = CreatInitWorkers(worker_counter++, workers);
    }

    for (auto it : workers)
    {
        std::cout << it.first << std::endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

我想创建一个像CreatInitWorkers函数一样的模板函数(正如它在星星之间显示的那样)。但是我不知道如何将Probe类转移到new操作中,因为对于我的程序来说,还有其他类需要在那里。有什么办法可以做到吗?谢谢。

Igo*_*nik 5

沿着这些路线的东西:

template<class T> T Create(int counter, T& produced)
{
    using C = std::remove_pointer_t<std::decay_t<decltype(produced[counter])>>;
    produced[counter] = new C();
    return produced;
}
Run Code Online (Sandbox Code Playgroud)

演示