I want to use a map to refer to a type specifier mainly to shorten my code from multiple uses of
std::unique_ptr< Class >(new class1);
to
std::unique_ptr< Class >(new sampleMap[enum1]);
and then define my map so that it refers each enum value (enum1, enum2, ...) to my classes (class1, class2, ...).
But I cannot define my map with the values being a type name like this
std::map < int, Class > mapName {
{0, class1},
{0, class1},
...
};
since type name is not allowed in maps.
The main reason I'm looking for an answer for this is to make my code more succinct by replacing a series of "if/else if" statements or "switch-case" statements into only one line of code where the output std::unique_ptr<Class>(new class1); is dynamically figured out through the map that I define. So, I just input the enum number and get the corresponding class instantiated for me. Otherwise, I would have to do this:
if (enum1 = 0)
{
std::unique_ptr< Class >(new class1);
}
else if (enum2 = 0)
{
std::unique_ptr< Class >(new class2);
}
(or a switch-case)
But I want to do all above in one line like this:
std::unique_ptr<Class>(new sampleMap[enum1]);
plus the map declaration.
Any clue how this could be done?
You cannot easily implement an std::map that will return types as values the way you are trying to do it. You would need to implement your own class that would represent types as values. However, since your goal seems to be to create instances of objects where the concrete type depends on a value, an easily solution is to make a map of functions instead. This assumes that all the types you want to support derive from a common type. Each value can hold a function which constructs the correct object. If your types do not derive from a common type, then you will need to preform further type erasure (perhaps with std::any).
#include <functional>
#include <iostream>
#include <map>
#include <memory>
// Simple set of classes
// Class is the base type
// Class1 and Class2 derive from Class
struct Class { virtual void func() = 0; };
struct Class1 : Class {
void func() override { std::cout << "Class1\n"; }
};
struct Class2 : Class {
void func() override { std::cout << "Class2\n"; }
};
// A map of factory functions
const std::map<int, std::function<std::unique_ptr<Class>()>> mapName = {
{ 1, []() {return std::make_unique<Class1>(); } },
{ 2, []() {return std::make_unique<Class2>(); } }
};
int main()
{
auto foo = mapName.at(2)(); // Make an object of type associated with the value 2
foo->func(); // Prints "Class2\n"
return 0;
}
Depending on where you want to use this code, you might want to do this with an if-else chain. std::functions are usually very difficult for the compiler to optimize, so if you expect this code to be called frequently enough, it's probably more efficient to just code it out:
(using #FrançoisAndrieux's example)
#include <iostream>
#include <memory>
#include <stdexcept>
// Simple set of classes
// Class is the base type
// Class1 and Class2 derive from Class
struct Class {
virtual void func() = 0;
};
struct Class1 : Class {
void func() override { std::cout << "Class1\n"; }
};
struct Class2 : Class {
void func() override { std::cout << "Class2\n"; }
};
std::unique_ptr<Class> make_class(int i)
{
if (i == 0) return std::make_unique<Class1>();
else if (i == 1) return std::make_unique<Class2>();
throw std::out_of_range{ "Asked to construct an unknown type" };
}
int main()
{
auto foo = make_class(1); // Make an object of type associated with the value 1
foo->func(); // Prints "Class2\n"
return 0;
}
If the number of values is large, you might gain by doing a binary search (or just a switch):
// If there are 128 elements, for example
if (!(0 <= i && i < 128)) throw std::out_of_range{ "..." };
if (i < 64) {
if (i < 32) {
...
} else {
...
}
} else {
...
}
It's messy but it's only in one place.
To make a more optimizable version, you can do some minimal metaprogramming / expression templates:
#include <iostream>
#include <memory>
#include <stdexcept>
#include <type_traits>
#include <utility>
// Simple set of classes
// Class is the base type
// Class1 and Class2 derive from Class
struct Class {
virtual void func() = 0;
};
struct Class1 : Class {
void func() override { std::cout << "Class1\n"; }
};
struct Class2 : Class {
void func() override { std::cout << "Class2\n"; }
};
template<typename R, typename SwBase, typename T, typename F>
struct Switch
{
SwBase base;
T value;
F fn;
constexpr Switch(SwBase base, T value, F fn)
: base{ std::move(base) }
, value{ std::move(value) }
, fn{ std::move(fn) }
{}
constexpr R operator()(T val) const {
if (value == val) return fn();
return base(val);
}
};
template<typename R, typename SwBase, typename T, typename F>
constexpr auto make_switch_impl(SwBase&& swb, T&& t, F&& f)
{
return Switch<R, std::decay_t<SwBase>, std::decay_t<T>, std::decay_t<F>> {
std::forward<SwBase>(swb),
std::forward<T>(t),
std::forward<F>(f),
};
}
template<typename R>
constexpr auto make_switch(char const* failMsg)
{
return [=](auto&&) -> R { throw std::out_of_range{ failMsg }; };
}
template<typename R, typename T, typename F, typename... Args>
constexpr auto make_switch(char const* failMsg, T&& val, F&& fn, Args&&... args)
{
return make_switch_impl<R>(
make_switch<R>(failMsg, std::forward<Args>(args)...),
std::forward<T>(val),
std::forward<F>(fn)
);
}
auto make_class(int i)
{
return make_switch<std::unique_ptr<Class>>(
"Asked to construct an unknown type",
0, [] { return std::make_unique<Class1>(); },
1, [] { return std::make_unique<Class2>(); }
)(i);
}
int main()
{
auto foo = make_class(1); // Make an object of type associated with the value 1
foo->func(); // Prints "Class2\n"
return 0;
}
The switch statement would turn into this:
auto make_class(int i)
{
return make_switch<std::unique_ptr<Class>>(
"Asked to construct an unknown type",
0, [] { return std::make_unique<Class1>(); },
1, [] { return std::make_unique<Class2>(); }
)(i);
}
You could also store the "switch" separately, although this makes it less optimizable (down to roughly the same level as François Andrieux's solution):
const auto mapName = make_switch<std::unique_ptr<Class>>(
"Asked to construct an unknown type",
0, [] { return std::make_unique<Class1>(); },
1, [] { return std::make_unique<Class2>(); }
);
auto make_class(int i)
{
return mapName(i);
}
This version, and also raw if-else chains, let the compiler optimize the make_class function to the equivalent of a switch statement. Also, the main function:
int main()
{
auto foo = make_class(1); // Make an object of type associated with the value 1
foo->func(); // Prints "Class2\n"
return 0;
}
Can be optimized to the equivalent of:
int main()
{
std::cout << "Class2\n";
return 0;
}
Whereas storing the std::function or the other less efficient tricks I've mentioned makes it much more difficult for the compiler to optimize it fully (I haven't found one that does).
Note that out of GCC, Clang, Visual C++, and the Intel compiler, only Clang was able to completely optimize the main function using this Switch struct. GCC and Visual C++ were able to optimize it to a call to Class2's func(). The Intel compiler doesn't seem to have optimized it at all (but maybe I don't know the right flags for it)
Related
I have
class ClassA {};
class ClassB {};
auto func_a() -> ClassA {
return ClassA(); // example implementation for illustration. in reality can be different. does not match the form of func_b
}
auto func_b() -> ClassB {
return ClassB(); // example implementation for illustration. in reality can be different. does not match the form of func_a
}
I want to be able to use the syntax
func<ClassA>() // instead of func_a()
func<ClassB>() // instead of func_b()
(this is as part of a bigger template)
but I don't know how to implement this template specialization for the function alias.
Help? What is the syntax for this?
[Edit] The answers posted so far do not answer my question, so I'll edit my question to be more clear.
The actual definition of func_a and func_b is more complex than just "return Type();". Also they cannot be touched. So consider them to be
auto func_a() -> ClassA {
// unknown implementation. returns ClassA somehow
}
auto func_b() -> ClassB {
// unknown implementation. returns ClassB somehow
}
I cannot template the contents of func_a or func_b. I need the template for func<ClassA|ClassB> to be specialized for each one of the two and be able to select the correct one to call
You might do something like (c++17):
template <typename T>
auto func()
{
if constexpr (std::is_same_v<T, ClassA>) {
return func_a();
} else {
return func_b();
}
}
Alternative for pre-C++17 is tag dispatching (which allows customization point):
// Utility class to allow to "pass" Type.
template <typename T> struct Tag{};
// Possibly in namespace details
auto func(Tag<ClassA>) { return func_a(); }
auto func(Tag<ClassB>) { return func_b(); }
template <typename T>
auto func() { return func(Tag<T>{}); }
You can do it like this :
#include <iostream>
#include <type_traits>
class A
{
public:
void hi()
{
std::cout << "hi\n";
}
};
class B
{
public:
void boo()
{
std::cout << "boo\n";
}
};
template<typename type_t>
auto create()
{
// optional : if you only want to be able to create instances of A or B
// static_assert(std::is_same_v<A, type_t> || std::is_same_v<B, type_t>);
type_t object{};
return object;
}
int main()
{
auto a = create<A>();
auto b = create<B>();
a.hi();
b.boo();
return 0;
}
In some code that I was reading, I found the usage of empty struct like so:
struct input_iterator_tag { };
struct bidirectional_iterator_tag { };
struct random_access_iterator_tag { };
So in the rest of the code, it was used as what they call tag dispatching.
I was wondering if there is other usage of empty structs.
from an older post I saw that :
three major reasons we use empty structs in C++ are:
a base interface
a template parameter
a type to help overload resolution. (tag dispatching if I am not wrong)
Could someone explain that please?
a type to help overload resolution. (tag dispatching if I am not wrong)
When you want to use a complex template specialization pattern on some function, you don't try to go at it directly, but rather write:
template <typename T1, typename T2, other things maybe>
int foo(T1 param1, T2 param2 and so on)
{
using tag = put your complex stuff here, which produces an empty struct
detail::foo_impl(tag, std::forward<T1>(param1), std::forward<T2>(param2) and so on);
}
Now, the compiler doesn't have to decide between competing choices of template specialization, since with different tags you get incompatible functions.
a base interface
struct vehicle {
// common members and methods,
// including (pure) virtual ones, e.g.
virtual std::size_t num_maximum_occupants() = 0;
virtual ~vehicle() = default;
};
namespace mixins {
struct named { std::string name; };
struct wheeled { int num_wheels; public: rev() { }; };
} // namespace mixins
struct private_sedan : public vehicle, public wheeled, named {
// I dunno, put some car stuff here
//
// and also an override of `num_maximum_occupants()`
};
Making the base struct completely empty is perhaps not that common, but it's certainly possible if you use mixins a lot. And you could check for inheritance from vehicle (although I'm not sure I'd do that).
a template parameter
Not sure what this means, but venturing a guess:
template <typename T>
struct foo { };
template <typename T, typename N>
struct foo<std::array<T, N>> {
int value = 1;
};
If you now use foo<T>::value in a function, it will work only if T is int with few (?) exceptions.
I also tried to come up with examples:
as a base interface
// collection of very abstract vehicles
#include <vector>
struct Vehicle {};
struct Car : Vehicle {
int count_of_windows;
};
struct Bike : Vehicle {
int size_of_wheels;
};
std::vector<Vehicle> v{Bike{}, Car{}};
as a template parameter
// print same number in 3 different formats
#include <iostream>
struct dec {};
struct hex {};
struct octal {};
template<typename HOW = dec>
void print_me(int v);
template<>
void print_me<dec>(int v) {
auto f = std::cout.flags();
std::cout << std::dec << v << std::endl;
std::cout.flags(f);
}
template<>
void print_me<hex>(int v) {
auto f = std::cout.flags();
std::cout << std::hex << v << std::endl;
std::cout.flags( f );
}
template<>
void print_me<octal>(int v) {
auto f = std::cout.flags();
std::cout << std::oct << v << std::endl;
std::cout.flags(f);
}
int main() {
print_me(100);
print_me<hex>(100);
print_me<octal>(100);
}
a type to help overload resolution
// add a "noexcept" qualifier to overloaded function
// the noexcept version typically uses different functions
// and a custom "abort" handler
#include <iostream>
struct disable_exceptions {};
void is_number_1() {
int v;
std::cin >> v;
if (v != 1) {
throw new std::runtime_error("AAAA");
}
}
void is_number_1(disable_exceptions) noexcept {
int v;
// use C function - they don't throw
if (std::scanf("%d", &v) != 1) {
std::abort();
}
if (v != 1) {
std::abort();
}
}
int main() {
is_number_1();
is_number_1(disable_exceptions());
}
The example about "tag dispatching" can be found on cppreference iterator_tags. The iterator_category() member of an iterator is used to pick a different overload. That way you could write a different algorithm if for example iterator is forward_iterator, where you can only go forward, or it is a bidirectional_iterator, where your algorithm could change because you may walk back.
I have a non-type template class template<std::size_t N> Derived<N> which derives from some non-template base class Base:
class Base
{
public:
double some_value;
// Some methods and variables that do not depend on N
// I wish to keep these in a non-templated class
virtual const size_t get_N() = 0;
virtual ~Base() = default;
Base(double value): some_value {value} {};
};
template <std::size_t N>
class Derived: public Base
{
public:
double some_other_value;
// Some functions and variables, for which
// the types and actions depend on N
const size_t get_N() override
{
return N;
}
Derived(double value1, double value2): Base(value1), some_other_value {value2} {};
};
Now I have a function call_by_base(Base& my_base), which only uses member variables/functions declared in Base. The only exception to this, is a call to template<std::size_t N> void call_by_derived(Derived& my_derived). Since almost the entire function call_by_base is independent of the template parameter, I would prefer to keep this function non-templated.
I tried to achieve the above with implementations along the lines of:
template<std::size_t N>
void call_by_derived(Derived<N>& my_derived)
{
std::cout << "in call_by_derived" << std::endl;
// Methods that use the functions and variables in Derived.
}
void broken_call_by_base(Base& my_base)
{
std::cout << "in call_by_base" << std::endl;
// Manipulations independent of child
// type Derived<N>
auto derived = dynamic_cast<Derived<my_base.get_N()>&>(my_base);
call_by_derived(derived);
// Manipulations independent of child
// type Derived<N>
}
When I try to compile this code, I get error: expression ‘Base::get_N’ is not a constant-expression. I tried to resolve this error by trying to change different thing, both in my Base and Derived class. This was all without success.
I managed to get the following alternative to work:
void working_call_by_base(Base& my_base)
{
std::cout << "in call_by_base" << std::endl;
if(my_base.get_N()==2)
{
auto derived = dynamic_cast<Derived<2>&>(my_base);
call_by_derived(derived);
}
if(my_base.get_N()==3)
{
auto derived = dynamic_cast<Derived<3>&>(my_base);
call_by_derived(derived);
}
}
This is however very tedious, especially when N can take on many more values. Is there any way to get a function along the lines of broken_call_by_base working? That is: How can I downcast a non-template Base to a non-type template Derived<N>?
ps. Only object of the Derived<N> type will be created. This is the code in main to test:
int main()
{
Derived<3> test(1.0,2.0);
working_call_by_base(test);
broken_call_by_base(test);
call_by_derived(test);
}
It'll be best if you can use a virtual member function to avoid the if/else checks.
If that is not an option for some reason, use of a callback/plugin mechanism is the most appropriate.
You provide a mechanism in the Base-specific code base to allow other classes/functions/modules to register functions that are appropriate for the type they know about.
In the Base-specific code, you keep track of the registered functions using a key that is appropriate for Base.
In the Base-specific code, you check whether a function has been registered for the key. If it has, you call the function with the suitable arguments.
In the derived class specific code, you can downcast to the appropriate class. If the downcast succeeds, in most cases it should, you proceed to use the derived class.
This pattern strictly adheres to the Open-Closed Principle and is one of my favorite coding patterns.
In your case, the key is N.
Here's an example program that demonstrates the concept.
#include <iostream>
// Base.hpp
// #pragma once
#include <cstdint>
class Base
{
public:
double some_value;
// Some methods and variables that do not depend on N
// I wish to keep these in a non-templated class
virtual const size_t get_N() = 0;
virtual ~Base() = default;
Base(double value): some_value {value} {};
typedef void (*CallbackFunctionType1)(Base& b);
static void registerCallback(std::size_t N, CallbackFunctionType1 f);
};
void call_by_base(Base& my_base);
// Base.cpp
#include <map>
namespace BaseNS
{
using CallbackFunctionType1Map = std::map<std::size_t, Base::CallbackFunctionType1>;
CallbackFunctionType1Map& getCallbackFunctionType1Map()
{
static CallbackFunctionType1Map theMap;
return theMap;
}
}
void Base::registerCallback(std::size_t N, CallbackFunctionType1 f)
{
BaseNS::CallbackFunctionType1Map& theMap = BaseNS::getCallbackFunctionType1Map();
theMap[N] = f;
}
void call_by_base(Base& my_base)
{
std::cout << "In call_by_base" << std::endl;
BaseNS::CallbackFunctionType1Map& theMap = BaseNS::getCallbackFunctionType1Map();
BaseNS::CallbackFunctionType1Map::iterator iter = theMap.find(my_base.get_N());
if ( iter != theMap.end() )
{
iter->second(my_base);
}
}
// Derived.hpp
// #pragma once
template <std::size_t N>
class Derived: public Base
{
public:
double some_other_value;
// Some functions and variables, for which
// the types and actions depend on N
const size_t get_N() override
{
return N;
}
Derived(double value1, double value2): Base(value1), some_other_value {value2} {};
};
// Derived.cpp
// Register call back functions for Derived.
namespace DerivedNS
{
template <std::size_t N>
void call_by_derived(Derived<N>& derived)
{
std::cout << "In call_by_derived<" << N << ">" << std::endl;
// Use derived.
}
template <std::size_t N>
void call_for_derived(Base& my_base)
{
Derived<N>* d_ptr = dynamic_cast<Derived<N>*>(&my_base);
if ( d_ptr != nullptr )
{
call_by_derived(*d_ptr);
}
else
{
// Error.
}
}
bool registerCallbackFunctions()
{
// Register callbacks for as many values of N as needed.
Base::registerCallback(1, call_for_derived<1>);
Base::registerCallback(2, call_for_derived<2>);
Base::registerCallback(3, call_for_derived<3>);
Base::registerCallback(4, call_for_derived<4>);
Base::registerCallback(5, call_for_derived<5>);
return true;
}
bool dummy = registerCallbackFunctions();
}
int main()
{
Derived<1> d1(0, 0);
Derived<2> d2(0, 0);
Derived<10> d3(0, 0);
call_by_base(d1);
call_by_base(d2);
call_by_base(d3); // Does not go to call_by_derived.
}
Output:
In call_by_base
In call_by_derived<1>
In call_by_base
In call_by_derived<2>
In call_by_base
I want to write a function that return different types based on different input as below.
enum MyType
{
A,
B
};
template<MyType T> struct MyStruct
{
};
static auto createMyStruct(MyType t)
{
if(t==A)
return MyStruct<A>();
else
return MyStruct<B>();
}
It didn't work out because there are two return types for one auto. Is there any other way to do this?
There is absolutely no way of having a (single) function that returns different types based on a runtime decision. The return type has to be known at compile time. However, you can use a template function, like this (thanks to #dyp for making me simplify the code):
#include <iostream>
#include <typeinfo>
enum MyType
{
A,
B
};
template<MyType>
struct MyStruct {};
template<MyType type>
MyStruct<type> createMyStruct()
{
return {};
}
int main()
{
auto structA = createMyStruct<A>();
auto structB = createMyStruct<B>();
std::cout << typeid(structA).name() << std::endl;
std::cout << typeid(structB).name() << std::endl;
}
I am assuming you want to write code like this:
void foo (MyType t) {
auto x = createMyStruct(t);
//... do something with x
}
You are attempting to derive the right type for x at runtime. However, the return type of a function must be known at compile time, and the type resolution for auto is also determined at compile time.
You could instead restructure your code to be like this:
template<MyType T> struct MyStruct
{
//...
static void foo () {
MyStruct x;
//... do something with x
}
};
The idea is to write a single foo() function whose only difference is the type of thing it is manipulating. This function is encapsulated within the type itself. You can now make a runtime decision if you have a mapping between MyType and MyStruct<MyType>::foo.
typedef std::map<MyType, void(*)()> MyMap;
template <MyType...> struct PopulateMyMap;
template <MyType T> struct PopulateMyMap<T> {
void operator () (MyMap &m) {
m[T] = MyStruct<T>::foo;
}
};
template <MyType T, MyType... Rest> struct PopulateMyMap<T, Rest...> {
void operator () (MyMap &m) {
m[T] = MyStruct<T>::foo;
PopulateMyMap<Rest...>()(m);
}
};
template<MyType... Types> void populateMyMap (MyMap &m) {
PopulateMyMap<Types...>()(m);
}
//...
populateMyMap<A, B>(myMapInstance);
Then, to make a runtime decision:
void foo (MyType t) {
myMapInstance.at(t)();
}
I think you should learn abstract factory design pattern.
For use objects of type MyStruct<A> or MyStruct<B> you need common interface.
Common interface provided in abstract base class.
struct MyStruct
{
virtual ~MyStruct() {}
virtual void StructMethod() = 0;
};
struct MyStructA: public MyStruct
{
void StructMethod() override {}
};
struct MyStructB: public MyStruct
{
void StructMethod() override {}
};
std::unique_ptr<MyStruct> createMyStruct(MyType t)
{
if (t==A)
return std::make_unique<MyStructA>();
else
return std::make_unique<MyStructB>();
}
This is easier to explain with some code so I'll give an example first:
#include <iostream>
#include <vector>
class Base {
public:
int integer;
Base() : integer(0) {}
Base(int i) : integer(i) {}
};
class Double: public Base {
public:
Double(int i) { integer = i * 2; }
};
class Triple: public Base {
public:
Triple(int i) { integer = i * 3; }
};
template<typename T>
Base* createBaseObject(int i) {
return new T(i);
};
int main() {
std::vector<Base*> objects;
objects.push_back(createBaseObject<Double>(2));
objects.push_back(createBaseObject<Triple>(2));
for(int i = 0; i < objects.size(); ++i) {
std::cout << objects[i]->integer << std::endl;
}
std::cin.get();
return 0;
}
I am trying to make a function that will return a Base pointer to an object that is derived from Base. In the above code the function createBaseObject allows me to do that but it restricts me in that it can only create dervied classes that take a single argument into their constructor.
For example if I wanted to make a derived class Multiply:
class Multiply: public Base {
public:
Multiply(int i, int amount) { integer = i * amount; }
};
createBaseObject wouldn't be able to create a Multiply object as it's constructor takes two arguments.
I want to ultimately do something like this:
struct BaseCreator {
typedef Base* (*funcPtr)(int);
BaseCreator(std::string name, funcPtr f) : identifier(name), func(f) {}
std::string identifier;
funcPtr func;
};
then, for example, when I get input matching identifier I can create a new object of whatever derived class associates with that identifier with whatever arguments were input too and push it to the container.
After reading some of the replies I think something like this would suit my needs to be able to procedurally create an instance of an object? I'm not too wise with templates though so I do not know whether this is legal.
struct CreatorBase {
std::string identifier;
CreatorBase(std::string name) : identifier(name) {}
template<typename... Args>
virtual Base* createObject(Args... as) = 0;
};
template<typename T>
struct Creator: public CreatorBase {
typedef T type;
template<typename... Args>
Base* createObject(Args... as) {
return new type(as...);
}
};
Okay here's another semi-solution I've managed to come up with so far:
#include <boost\lambda\bind.hpp>
#include <boost\lambda\construct.hpp>
#include <boost\function.hpp>
using namespace boost::lambda;
boost::function<Base(int)> dbl = bind(constructor<Double>(), _1);
boost::function<Base(int, int)> mult = bind(constructor<Multiply>(), _1, _2);
Just this has the same limits as the original in that I can't have a single pointer that will point to both dbl and mult.
C++11 variadic templates can do this for you.
You already have your new derived class:
class Multiply: public Base {
public:
Multiply(int i, int amount) { integer = i * amount; }
};
Then change your factory:
template<typename T, typename... Args>
Base* createBaseObject(Args... as) {
return new T(as...);
};
And, finally, allow the arguments to be deduced:
objects.push_back(createBaseObject<Multiply>(3,4));
Live demo.
As others have said, though, it does all seem a little pointless. Presumably your true use case is less contrived.
Why not provide multiple overloads with templated parameters?
template<typename TBase, TArg>
Base* createBaseObject(TArg p1) {
return new TBase(p1);
};
template<typename TBase, TArg1, TArg2>
Base* createBaseObject(TArg p1, TArg2 p2) {
return new TBase(p1, p2);
};
Use variadic templates:
template <typename R, typename ...Args>
Base * createInstance(Args &&... args)
{
return new R(std::forward<Args>(args)...);
}
Usage: objects.push_back(createInstance<Gizmo>(1, true, 'a'));
It's a bit hard to see why you would want this, though, as you might as well just say:
objects.push_back(new Gizmo(1, true, 'a'));
Even better would be to declare the vector to carry std::unique_ptr<Base> elements.