Since you use unique_ptr<BaseComponent> , of course, there may be times when the conversion is not performed: the insertion of new data into the vector and the consumption of this data is performed in unrelated places and so that the compiler cannot enforce it.
The following is an example of an invalid click:
struct AnotherComponent : public Component<AnotherComponent> { virtual ~AnotherComponent () {} }; std::vector<std::unique_ptr<BaseComponent>> mComponents; mComponents.emplace_back(new AnotherComponent);
In this regard, the use of dynamic_cast will provide better protection against misuse of the as<T> function. Note that misuse cannot be intentional: at any time when the compiler cannot check the type for you and you have a potential type mismatch, you should prefer dynamic_cast<T>
Here's a short demo to show how dynamic_cast offer you a degree of protection.
source share