C++ Logo

std-discussion

Advanced search

Re: std::make_shared and type deduction

From: Hans Åberg <haberg-1_at_[hidden]>
Date: Fri, 10 Jul 2020 22:37:47 +0200
> On 10 Jul 2020, at 21:57, Kyle Knoepfel <kyleknoepfel_at_[hidden]> wrote:
>
> If I were in control of the type, then sure, that could work. But Foo<T> (from the original post) could represent any template (or type, for that matter), which I don't necessarily have control over. For example, I can't add new_p member functions to std::vector. The solution would be a free function, and Thiago's suggested such names as clone_unique(..)/clone_shared(..), which accurately describe the need.

The reason they should be in a class is to allow for polymorphic copying, if that is not the case, they can be external. To be explicit, I made the small working example below. Is that what you wanted?

--
#include <iostream>
#include <vector>
template <class T>
std::vector<T> make_foo() { return {1, 2, 3}; }
template <class A>
std::vector<A>* foo_p() { return new std::vector<A>(std::move(make_foo<A>())); }
int main() {
  auto fp = foo_p<int>();
  for (auto& i: *fp)
    std::cout << i << " ";
  std::cout << std::endl;
  return EXIT_SUCCESS;
}
--

Received on 2020-07-10 15:41:04