To move an existing Sum_Function
subclass object pointer into Functions
you can do like this:
void AddFunction(std::unique_ptr<Sum_Function>& func) {
Functions.emplace_back(std::move(func));
}
...
Container c;
auto f = std::make_unique<SumMaxSize>();
c.AddFunction(f);
... or like this, which requires the argument to be an rvalue reference, which in turn makes the pointer-stealing more obvious:
void AddFunction(std::unique_ptr<Sum_Function>&& func) {
Functions.emplace_back(std::move(func));
}
...
Container c;
auto f = std::make_unique<SumMaxSize>();
// c.AddFunction(f); // Error, f is an lvalue
c.AddFunction(std::move(f)); // OK, xvalue
c.AddFunction(std::make_unique<SumMaxSize>()); // OK, prvalue
You could also provide a convenience member function in Container
for creating it directly in the vector without the middle step:
template<typename T, class... Args>
void emplace_back(Args&&... args) {
Functions.emplace_back(std::make_unique<T>(std::forward<Args>(args)...));
}
And instead of doing make_unique
first and calling AddFunction
, just:
Container c;
c.emplace_back<SumMaxSize>();
The perfect forwarding in the emplace_back
function template above will also make the in-place construction to work for subclasses with constructors that takes arguments:
struct BiasedSumFunc : Sum_Function {
BiasedSumFunc(int bias) : bias_(bias) {}
private:
int bias_;
};
...
Container c;
c.emplace_back<BiasedSumFunc>( -5 );