marcoo
marcoo

Reputation: 869

Passing any object type to a function C++

I am using a library that provides different types of Signal Objects. The library has a method:

void sendSignal(boost::shared_ptr<ISignal>)

Each Signal object provided by the library implements the ISignal interface. The ISignal interface does not provide any cloning methods. However, all the objects that implement ISignal do have a copy constructor.

I want to create a function that takes any type that implements ISignal, clones that object by calling the copy constructor, and returns the new copied object. I want to call sendSignal multiple times on different copied objects.

The code currently calls the copy constructor of the different objects in multiple locations. I was hoping there is a simple way of perhaps passing template to a function and have that function copy that object for me, by assuming that the object has a copy constructor. However, my problem is I can't pass ISignal because that doesn't specify any copy constructor, and I can't pass a specific object that implements ISignal . Is there any way I can do this, without C++11?

Upvotes: 0

Views: 691

Answers (2)

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

Reputation: 275370

template<class XSignal,
  class=typename std::enable_if<
    std::is_base_of<ISignal,XSignal>::value
  >::type
>
std::shared_ptr<XSignal> CopySignal( XSignal const& signal ) {
  return std::make_shared<XSignal>(signal);
}

is a function that can accept an instance of any class derived from ISignal and produces a shared pointer copy.

You have to know the actual derived type at compile time to use this function.

Upvotes: 3

Sam Varshavchik
Sam Varshavchik

Reputation: 118310

A copy constructor of a base class has no means of copying the entire derived object that the base class is a part of. This goes for C++ or C++11. This is fundamental to C++.

The base class must define a virtual clone() method, or something of similar name, and each derived class must override clone() to construct another instance of the derived class on the heap, then return a pointer to it. That is the only portable way to do this in C++.

If the base class has at least one virtual method, you might be able to get away with writing an external implementation of clone() that tries a dynamic_cast to each possible derived class of the base class, and, if it succeeds, implements a derived class-specific object copy.

Upvotes: 0

Related Questions