template method overrides non-template method - c++

I want to put any kind of Object (Object, Object etc.) into one shared_ptr. So I created base class and use shared_ptr.
But, how can I declare
T getMember();
within the base class so I can call ObjectBase.getMember?
class ObjectBase
{
public:
//virtual getMember HOWTO?
};
template<typename T>
class Object : public ObjectBase
{
public:
Object(T x):member(x) { }
T getMember() { return member; }
private:
T member;
};

You can't. How should such a declaration look, that it can return all kinds of types? It's just not possible. You'd have to cast the ObjectBase* to the correct Object<T>* and then use the getMember function. It's only possible if all T share a common base class, so you could return a pointer to that. But that would put a strict constraint on T.

That cannot be done. The compiler must know upfront how many different virtual functions (and overloads) will be available, but in your case you are considering adding new virtual member functions on demand based on new potential instantiations of the derived type.
In most cases, keeping completely unrelated objects in the same container is not a good design option, but for the few cases where it actually is, you can use variant types (consider boost::any or boost::variant, depending on your actual requirements. That is a bundled up, tested implementation of a variant type that you might be able to directly use.

Related

Calling a member function from a base class pointer with varying parameters depending on the derived class

I'm pretty experienced in C++, but I find myself struggling with this particular design problem.
I want to have a base class, that I can stuff in a std::map, with a virtual function that can be called generically by a method that is querying the map. But I want to be able to call that function from a base class pointer with different parameters, depending on what the derived type is. Something functionally similar to the following wildly illegal example:
class Base
{
virtual void doThing() = 0;
}
class Derived1 : public Base
{
void doThing(int i, const std::string& s) {} // can't do that
}
class Derived2: public Base
{
void doThing(double d, std::vector<int>& v) {} // can't do that either
}
enum class ID = {
DERIVED1,
DERIVED2
}
std::map<ID, std::unique_ptr<Base> thingmap = { ... }
std::unique_ptr<Base>& getThing(int) { return thingmap[i] };
int main(int I, const char* argv[]) {
auto baseptr = getThing(DERIVED1);
baseptr->doThing(42, "hello world");
}
I don't want the caller to have to know what the derived type is, only that a Derived1 takes an int and a string. Downcasting isn't an option because the whole point of this is that I don't want the caller to have to specify the derived type explicitly. And C-style variable argument lists are yucky. :-)
Edited to clarify: I know exactly why the above can't possibly work, thank you. :-) This is library code and I'm trying to conceal the internals of the library from the caller to the greatest extent possible. If there's a solution it probably involves a variadic template function.
You can't do that.
Your map is filled with Base instances, so the class DO NOT have the required prototypes implemented in Derived1 or Derived2... And redefining overloaded methods do not implement the pure virtual method doThing, so Derived1 and Derived2 are still abstract classes and therefore cannot be instanciated.
Worst, your getThing function only deals with Base, so the compiler would NEVER allows you to use the overloaded signatures, since they don't exist AT ALL in Base. There is nothing to know the real class behind, since you don't use templates and implicit template argument deduction.
Your pattern cannot be done this way, period. Since you don't want to use neither downcasting nor explicitely specified child classes, you're stuck.
Even if you add all possible prototypes in Base, since it will be pure virtual methods, both derived classes will still be abstract classes. And if they aren't, then you'll never be able to know which one is a NOP and which one is implemented, since it will requires downcasting!
I think that you made a common mistake, even done by expert developers sometimes: you went into conception directly, BEFORE determining your real ROOT needs.
What you ask looks like the core system of a factory, and it's really not the good way to implement this design pattern and/or designing the specialized derived classes.

C++14 ignore return type in interface getter but specify it in implementation

I have three classes of objects:
class Foo: has a mesh, and I need to get that mesh;
class Bar: is a Foo, but has some further capabilities which Foo doesn't have;
class Baz: is a Foo, but has another completely independent set of capabilities which neither Foo nor Bar have.
All three classes need to have a way to give me their mesh which, however, can be implemented in many ways, of which I need (at the moment I can't see another way) to use at least 2 different ones, which are MeshTypeA and MeshTypeB.
I would like to have a common interface for different implementations of the same concept (getMesh), however, I can't use auto in a virtual method. I'm lacking the facility to make the code have sense. I would like to have:
class Foo
{
public:
virtual ~Foo() = 0;
virtual auto getMesh() const = 0; // doesn't compile
};
class Bar : public Foo
{
public:
virtual ~Bar() = 0;
virtual auto getMesh() const = 0; // doesn't compile
// other virtual methods
};
class ConcreteFooWhichUsesA : public Foo
{
public:
ConcreteFooWhichUsesA();
~ConcreteFooWhichUsesA();
auto getMesh() const override {return mesh_;};
private:
MeshTypeA mesh_;
};
class ConcreteBarWhichUsesB : public Bar
{
public:
ConcreteBarWhichUsesB();
~ConcreteBarWhichUsesB();
auto getMesh() const override {return mesh_;};
// other implementations of virtual methods
private:
MeshTypeB mesh_;
};
MeshTypeA and MeshTypeB are not exclusive to Foo, Bar, or Baz, which is to say all three could have both types of mesh. However I really don't care for which MeshType I get when I later use it.
Do I need to wrap MeshTypeA and MeshTypeB in my own MeshType? Is it a matter of templating the MeshType? I believe there is a way, however related questions aren't helping or I can't formulate my question in a meaningful enough way.
I have also found this where the author uses a Builder class and decltype, but I don't have such a class. Maybe that would be it? Do I need a MeshLoader sort of class as an indirection level?
If your MeshTypes all have a common (abstract) base class, then you can just return (a pointer or reference to) that in the virtual function defintions, and the derived classes can then return their concrete mesh types, and all will be well. If you have code that can work on any mesh type, it is going to need that abstract base anyways.
If your MeshTypes do not all have a common base class, why even have a getMesh method in Foo at all? Remove it and give each of the concrete classes it's own getMesh method that doesn't override (and has nothing in particular to do with the meshes in any other concrete class).
A function's return type is part of its interface. You can't just change it willy-nilly. More specifically, you cannot have a base class virtual method return one thing while an overridden version returns another. OK, you can, but only if the derived version's return type is convertible to the base class return type (in which case, calling through the base class function will perform said conversion on the overriding method's return type).
C++ is a statically typed language; the compiler must know what an expression evaluates to at compile time. Since polymorphic inheritance is a runtime property (that is, the compiler is not guaranteed to be able to know which override will be called through a base class pointer/reference), you cannot have polymorphic inheritance change compile-time constructs, like the type of a function call expression. If you call a virtual method of a base class instance, the compiler will expect this expression to evaluate to what that base class's method returns.
Remember: the point of polymorphic inheritance is that you can write code that doesn't know about the derived classes and have it still work with them. What you're trying to do violates that.

Base class pointer for a template class that uses template parameter in member data

For the following template class
template <class T> class Arbitrary {
protected:
vector<T> ObjectArray;
public:
Arbitrary(){}
};
I want to be able to have a vector of base class pointers, I know I need to use an interface class but I can't get it to work, any suggestions would be greatly appreciated.
[..] I want to eventually write vector<Arbitrary*> name;
Arbitrary is a template, not a type. To "obtain" a type from it, you need to "apply" it to another type (like int). This gives you Arbitrary<int> as "result" type. This process is called template instantiation.
If you want a vector with objects of any possible type that might have been instantiated from the template Arbitrary, then you need to give them a common type (such that every object "is a" object of that common type). This is because std::vector stores only objects of a single type.
To have the objects "behave" (in the sense of having some type) differently even though they "have" a common type, you need to make them (or rather their common type) polymorphic. This is done by giving the common type some virtual function. (And since you want to delete/destruct objects through the "interface" exposed by the common type you need to make the destructor virtual!)
struct ArbitraryBase {
// Add "common interface" functions here, as virtual
virtual ~ArbitraryBase() = 0; // pure virtual to avoid creating objects
};
inline ArbitraryBase​::~ArbitraryBase() {}
template<typename T>
struct Arbitrary : ArbitraryBase {
// whatever
};
Now, to actually be able to use that polymorphic property and not become victim of object slicing you need to use reference or pointer semantics:
std::vector<ArbitraryBase *> objects;
Instead of raw pointers you should consider smart pointers like std::unique_ptr<ArbitraryBase> if the objects vector should have ownership of the objects or otherwise use std::reference_wrapper<ArbitraryBase> in case lifetime of the objects is reliably handled by something else.
But if you don't add any common interface (more virtual member functions) in ArbitraryBase then you're basically reinventing std::any / boost::any. So better use those well tested implementations instead.

How to identify class type to cast a shared_ptr to that type

I have a class hierarchy and I want get shared from this and cast it to the specific class type. So I want this:
class A : public std::enable_shared_from_this
{
std::shared_ptr<A> getSharedFromThis()
{
return std::static_pointer_cast<A>(shared_from_this());
}
};
class B : public A
{
std::shared_ptr<B> getSharedFromThis()
{
return std::static_pointer_cast<B>(shared_from_this());
}
};
In superclass I can write a templated variant but it is still not cool:
template <typename T>
std::shared_ptr<T> getSharedFromThis()
{
return std::static_pointer_cast<T>(shared_from_this());
}
How can I make it generic so that it will understand that it is in class B and cast to B the shared_ptr and now write the same logic in 100 classes that are in the same hierarchy.
You are looking for covariant return type wise smart pointers. That would be a nice feature, but you cant do it. The only way it could work is having a hierarchical relationship between shared_ptr<A> and shared_ptr<B>, which will not be the case in any near future.
You must either stick to the parent class template or use a wrapper object able to implement the covariant return type paradigm (that would mean careful declarations and possible mistakes due to copypasta).
std::enable_shared_from_this is not used correctly in your example since it is a templated class.
Be careful to use a dynamic_pointer_cast if the getter lays in the parent class.
It seems your key problem is deducing the type which called the templated getSharedFromThis(). Since the member function is implemented in a base class, it doesn't have any trace of derived class calling it - unless that is somehow specified. Using a non-member function calling the base function will take care of that neatly:
template <typename T>
auto getSharedFromThis(T& object) -> decltype(object.template getSharedFromThis<T>()) {
return object.template getSharedFromThis<T>());
}
This way there is no need to write anything for any of derived classes to get a getSharedFromThis() function yielding an appropriately type std::shared_ptr<T>. As a bonus, a similar hierarchy with a base exposing a getSharedFromThis() function can use the same function. You might want to overload the function with a pointer type so you can use getSharedFromThis(this) instead of getSharedFromThis(*this) in member functions.

inheritance and polymorphism c++ [duplicate]

This question already has answers here:
What is the main difference between Inheritance and Polymorphism?
(18 answers)
Closed 9 years ago.
I read up on inheritance and polymorphism but I still can't distinguish what's the difference between both of them.
From what I knew, inheritance is e.g(a derived class inheritance methods from base class and method overriding can be performed as well.) so then what is polymorphism? are both inheritance and polymorphism somehow have the meaning?
Please correct me as I know that I am wrong. Thanks
In this case, we have inheritance but no polymorphism:
struct SimpleBase {
int i;
int get() const { return i; }
};
struct SimpleDerived: public SimpleBase {
int get() const { return i + 7; }
};
an instance of SimpleBase (or a reference or pointer to it) is always exactly that, and the derived class can't change its behaviour. For example:
int foo(SimpleBase const &obj) { return obj.get(); }
will always call SimpleBase::get, even if I pass in an instance of the derived type.
Conversely, with polymorphism, a derived class can override base class methods with its own versions:
struct PolyBase {
int i;
virtual int get() const { return i; }
};
struct PolyDerived {
int get() const { return i + 7; }
};
int foo(PolyBase const &obj) { return obj.get(); }
Now foo calls a different method depending on the derived type passed in, without knowing which derived type it is.
So with polymorphism, a whole family of types can share a common interface, and you can write code once that operates on the interface, without having to know about all the different derived types.
The form of polymorphism shown above is run-time polymorphism: it generates code that figures out which implementation of each virtual function to call when it runs.
There is also compile-type polymorphism, which doesn't require inheritance at all, and instead uses templates.
Say you want to write a sorted container (like std::map) - you don't want to limit it to storing a particular data type, but you do need some way to compare two elements to see which is bigger.
The run-time approach might provide an abstract base class, like
struct LessThanComparable {
virtual bool operator< (LessThanComparable const &) const = 0;
};
and require every type you want to put in your container, to derive from this and implement operator<. Then, you can write if (a < b) in your container code, and the right function for the type you're storing will be called (*).
// requires inheritance from abstract base class,
// uses virtual call to operator<
bool less_than(LessThanComparable const &a, LessThanComparable const &b) {
return a < b;
}
The compile-type approach actually used (**) in the STL is to state that every stored type must model the LessThanComparable concept, by providing a suitable operator<. However, this is resolved at compile time, and no common base class is required.
// doesn't require any inheritance, doesn't use virtual function call,
template <typename T>
bool less_than(T const &a, T const &b) { return a < b; }
(*) note also that implementing operator< isn't trivial, because a < b can be called when a and b have different derived types. In the template version, we know they both have the same type T.
(**) ok, so the default std::less has the LessThanComparable requirement, or you can provide an alternative StrictWeakOrdering.
In farmer`s words, polymorphism is when you work with "base" class (called an interface in some cases) without knowing what the actual implementation really is. Inheritance can be used with or without polymorphism (i.e. when you use inheritance but always know what specific class of object you are dealing with, even if it is inherited from something else, is not a polymorphism). But polymorphism cannot be used without inheritance (it just stops making any sense).
Polymorphism allows you to morph the class back and forth between its inherited parent classes. The following is legal, if Dog and Cat class inherits from Animal
void takes_animal(Animal &animal) { }
Dog dog;
Cat cat;
takes_animal(dog);
takes_animal(cat);
Inheritance is an implementation technique. Polymorphism is an
aspect of one of the things you can implement with it. (It's
not the only thing. For example, inheriting from
std::iterator has nothing to do with polymorphism.)
Your are right about inheritance but it is not that simple. Overloading and Overriding are also important functions of inheritance. While, polymorphism is about creating polymorphic arrays like if parent class is fruits and apples are objects then you can define objects as type of fruits and call general function. Also creating pure virtual function will prevent parent class to make it's instances.