Search code examples
c++classnew-operatorfunction-templates

How to transfer a class type to a function template for new operation as a parameter?


I have a piece of c++ code:

#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;
    }
}

I want to create a template function (as it shows between the stars) like the CreatInitWorkers function. But I don't know how to transfer the Probe class to the new operation because for my program there are still other classes needed to be there. Is there any way can do it? Thanks.


Solution

  • Something along these lines:

    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;
    }
    

    Demo