Reputation: 5809
I'm very new to C++11, 'still very much experimenting with the extensions. I find the auto
keyword very convenient, particularly when dealing with template variables. This means that given
template<typename ... Types>
struct Foo
{
};
template<typename ... Types>
Foo<Types ...>* create( Types ... types ... )
{
return new Foo<Types ...>;
}
I can now make the assignment
auto t1 = create( 'a' , 42 , true , 1.234 , "str" );
instead of
Foo<char, int, bool, double , const char*>* t2 = create( 'a' , 42 , true , 1.234 , "str" );
The problem now is that because t1
is a pointer I'd like to hold it in a shared_ptr
as Herb Sutter recommended. Therefore, I'd like to store the return value of create()
in a shared_ptr
without having to name the template argument types, as in t2
.
Upvotes: 2
Views: 1619
Reputation: 5809
This is too long to post as a comment. Therefore I'm posting it here instead. Besides it might be an answer.
@nosid why not the following. Its less convoluted.
template<typename ... Types>
struct Foo
{
Foo( Types ... types ... ) : m_data( types ...)
{
}
std::tuple<Types...> m_data;
};
template<typename ... Types>
std::shared_ptr<Foo<Types ...> > create( Types ... types ... )
{
return std::make_shared<Foo<Types ...> >( types ... );
}
Upvotes: 0
Reputation: 50034
Avoid using raw pointers all together. Use std::make_shared
and make_unique
(not right in the standard) instead of new
. Then auto
will work nicely. E.g.
template <typename ...Args>
auto create(Args&&... args)
-> std::shared_ptr<Foo<typename std::decay<Args>::type...>>
{
return std::make_shared<Foo<typename std::decay<Args>::type...>>(
std::forward<Args>(args)...);
}
Upvotes: 2