我对 C++11 非常陌生,“仍在尝试扩展”。我发现 auto
关键字非常方便,特别是在处理模板变量时。这意味着给定
template<typename ... Types>
struct Foo
{
};
template<typename ... Types>
Foo<Types ...>* create( Types ... types ... )
{
return new Foo<Types ...>;
}
我现在可以进行作业
auto t1 = create( 'a' , 42 , true , 1.234 , "str" );
而不是
Foo<char, int, bool, double , const char*>* t2 = create( 'a' , 42 , true , 1.234 , "str" );
现在的问题是,因为 t1
是一个指针,我想按照 Herb Sutter 的建议将其保存在 shared_ptr
中。因此,我想将 create()
的返回值存储在 shared_ptr
中,而不必命名模板参数类型,如 t2
中所示>.
最佳答案
避免一起使用原始指针。使用 std::make_shared
和 make_unique
(不符合标准)而不是 new
。那么 auto
就会很好地工作。例如
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)...);
}
关于c++ - 从函数返回一个shared_ptr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12992285/