Skip to content

Instantly share code, notes, and snippets.

@etam
Created September 1, 2015 08:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save etam/fa02438e1c03bb9e7d2a to your computer and use it in GitHub Desktop.
Save etam/fa02438e1c03bb9e7d2a to your computer and use it in GitHub Desktop.
Make unique with cast
#include <iostream>
#include <memory>
#include <type_traits>
class Base
{
public:
virtual void foo() const = 0;
};
class Derived
: public Base
{
private:
int i;
public:
explicit
Derived(int _i)
: i(_i)
{}
virtual void foo() const override
{
std::cout << __PRETTY_FUNCTION__ << ' ' << i << '\n';
}
};
template <class BaseT, class DerivedT, typename... Args>
std::enable_if_t<std::is_convertible<DerivedT*,BaseT*>::value, std::unique_ptr<BaseT>> make_unique_as(Args&&... args)
{
return std::make_unique<DerivedT>(std::forward<Args>(args)...);
}
int main()
{
const auto obj = make_unique_as<Base, Derived>(5);
obj->foo();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment