c++ - Having a single method in a base class able to allocate for child classes -


i'm trying have common base/helper class allocates shared_ptrs calling class, i'm having problems getting work in derived classes.

#include <memory>  template<typename t> struct spalloc {      virtual ~spalloc() {}      template<typename ...args>     static std::shared_ptr<t>     alloc(args&&... params) {         return std::make_shared<t>(std::forward<args>(params)...);     }       template<class u, typename ...args>     static std::shared_ptr<u>     alloc(args&&... params) {         return std::make_shared<u>(std::forward<args>(params)...);     } };  class base : public spalloc<base> { public:     virtual ~base() {}; };  class child : public base { public:     virtual ~child() {}; };  typedef std::shared_ptr<base> pbase; typedef std::shared_ptr<child> pchild;  int main() {     pbase base = base::alloc();     pchild child = child::alloc(); } 

i understand class base : public spalloc<base> means t in template going base, why created second alloc. second alloc needs called child::alloc<child>().

is there way write alloc compiler can deduce class i'm calling alloc with?

short answer: no, there isn't.

long answer: point alloc not aware of child unless explicitly told, information come from? call child::alloc() call base::alloc(), call spalloc<base>::alloc() , there, information child lost.

the easiest solution using free function, function exists , it's called: std::make_shared. maybe consider using directly , safe trouble spalloc altogether.

alternatively, if want overwrite spalloc<t>::alloc() each child, won't need base class spalloc @ all, add method each class, that's easier using base class.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -