Optimizer agnostic initialisation

Excuse the terminology. What I’m trying to do is initialise an empty optimizer so that I can later assign one. I’ll outline what I mean with some (pseudo-) code:

void func(string optimizer_type){

    torch::optim::Optimizer opt;

    if(optimizer_type="SGD"){
        opt = torch::optim::SGD(params, 0.01);
    }
   else{
       opt = torch::optim::Adam(params);
   }
   // Use opt
}

But optim::Optimizer is an abstract class and I can’t assign it this way.

Maybe more of an OOP question, but how can I get this to work in Libtorch without changing parts of the library?

I would use shared pointer, something like this

void func(std::string optimizer_type) 
{
	std::shared_ptr<torch::optim::Optimizer> opt = nullptr;
	if (optimizer_type == "SGD") 
	{
		opt = std::make_shared<torch::optim::SGD>(model.parameters(), 0.01);
	}
	else 
	{
		opt = std::make_shared<torch::optim::Adam>(model.parameters());
	}
}