Created
September 1, 2015 08:32
-
-
Save etam/fa02438e1c03bb9e7d2a to your computer and use it in GitHub Desktop.
Make unique with cast
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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