nyarlathotep108
nyarlathotep108

Reputation: 5521

Generic way of constructing smart pointed data types as well as normal data types

I would like to write a generic way for constructing a type T taking into account the case in which T is a smart pointer of the data I actually want to construct. Something like:

template < typename T, typename... Args >
auto
create( Args... args )
{
    return T{args...};
}

template < typename std::unique_ptr< typename T >, typename... Args >
auto
create( Args... args )
{
    return std::make_unique< T >( args... );
}

template < typename std::shared_ptr< typename T >, typename... Args >
auto
create( Args... args )
{
    return std::make_shared< T >( args... );
}

This way it will of course not compile. It is just to explain the rough idea. I need two more specific overloads, which are still generic enough to do the job.

Caller code should be able to do something like this:

const SomeType x1 = create<SomeType>(1, 2, 3);
const std::unique_ptr<SomeType> x2 = create<std::unique_ptr<SomeType>>(1, 2, 3);

Upvotes: 0

Views: 32

Answers (1)

Jarod42
Jarod42

Reputation: 217810

You might use overload that way, with some indirection:

template <typename T> struct Tag{};

template <typename T, typename... Args>
auto create_impl(Tag<T>, Args&&... args)
{
    return T{std::forward<Args>(args)...};
}

template < typename T, typename... Args >
auto create_impl(Tag<std::unique_ptr<T>>, Args&&... args)
{
    return std::make_unique<T>(std::forward<Args>(args)...);
}
template < typename T, typename... Args >
auto create_impl(Tag<std::shared_ptr<T>>, Args&&... args)
{
    return std::make_shared<T>(std::forward<Args>(args)...);
}

template <typename T, typename... Args>
auto create(Args&&... args)
{
    return create_impl(Tag<T>{}, std::forward<Args>(args)...);
}

Upvotes: 1

Related Questions