0

I have a vector of unique_ptrs to objects that share a common base class. I would like to iterate through the vector and call the correct overload of a function, based on the stored type. The problem is that this function is not a member of the class (for those of you who enjoy talking design patterns: imagine I'm implementing a visitor class and f is the Visit method). Consider the following code example (or try it online):

#include <iostream>
#include <memory>
#include <vector>
using namespace std;

class Base{ public: virtual ~Base() {}; };
class A : public Base { public: virtual ~A() {} };
class B : public Base { public: virtual ~B() {} };
class C : public Base { public: virtual ~C() {} };

void f(Base* b) { cout << "Calling Base :(\n"; }
void f(A* a) { cout << "It is an A!\n"; }
void f(B* b) { cout << "It is a B\n"; }
void f(C* c) { cout << "It is a C!\n"; }

template<class Derived>
void push(vector<unique_ptr<Base>>& v, Derived* obj)
{
    v.push_back(std::unique_ptr<Derived>{obj});
}

int main() {
    vector<unique_ptr<Base>> v{};
    push(v, new A{});
    push(v, new B{});
    push(v, new C{});

    for(auto& obj : v)
    {
        f(obj.get());
    }

    return 0;
}

There are superficial differences with my code (f is a class method instead of a free function, I don't use using namespace std) but this shows the general idea. I see

Calling Base :(
Calling Base :(
Calling Base :(

whereas I would like to see

It is an A!
It is a B!
It is a C!

I would like to know if I can get the correct overload of f to be called (I would like to get rid of the f(Base*) version altogether).

One option would be manual typechecking along the lines of

     if(dynamic_cast<A>(obj) != nullptr) f((A*)obj);
else if(dynamic_cast<B>(obj) != nullptr) f((B*)obj);
...

but that is just plain ugly. Another option would be to move f to Base, but as said I am implementing a visitor pattern and would prefer to keep the Visit method out of the object tree I am visiting.

Thanks!

EDIT: Apparently my code example has given the impression that my types have to be non-virtual -- actually I do not have fundamental objections to adding a virtual method so I have added that to the code example.

5
  • This is overloading, not polymorphism. Polymorphism involves virtual member functions.
    – LogicStuff
    Jan 2, 2016 at 14:27
  • 8
    But the way to solve this is only dynamic_cast or polymorphism :) Overloading is a compile time matter, it can not possibly work here.
    – LogicStuff
    Jan 2, 2016 at 14:29
  • 1
    The correct solution imo. is to keep different types of objects in different vectors. Instead of throwing away the type information and then trying to reconstruct it you should just not throw it away.
    – nwp
    Jan 2, 2016 at 14:33
  • @nwp but the order is important too. Imagine the vector is a list of arithmetic operations that I want to perform in order, and my f is a visitor method that will print a user-readable representation in one case, and perform the calculations on some input stack in another case. Or the vector is a list of statements (variable declaration, expression statement, loop statement)) in an AST (abstract syntax tree) and I have different choices of f for interpreting or formatting the statements. Any suggestion how to implement your suggestion then?
    – CompuChip
    Jan 2, 2016 at 14:37
  • You want to avoid dynamic_cast because it's "ugly", yet look for manual re-implementations of the same feature (type identification at run-time). All solutions you will get will in some way or the other encode information about the concrete types of the vector elements. The big advantage of dynamic_cast is that the compiler does everything for you, bug-free. Jan 2, 2016 at 15:27

4 Answers 4

2

In order to be able at run-time to select the right function you need to have some virtual functions (unless you want to write yourself some type information function in your object and add some dispatching overhead).

The easiest approach would be to make f() a virtual member function of your base class and provide overriden version for each of the derived types. But you have eliminated this approach.

Another possible solution could be to make use of a double-dispatch like technique using a virtual dispatching function like this:

class Base { 
public:  
   virtual void callf() { f(this); } 
   virtual ~Base() {}
}
class A : public Base {
public: 
   void callf() override { f(this) };  // repeat in all derivates !  
}
class B : public Base {
public: 
   void callf() override { f(this) };  // repeat in all derivates !   
}
...
void F(Base *o) {  // this is the function to be called in your loop 
    o->f();        
}

The trick is that the compiler will find the right f() function in each callf() function, using the real type of this.
The F() function will then call the virtual dispatching function, making sure that it's the one corresponding to the real type of the object at execution time.

3
  • That's still a virtual call, just hidden inside a function. Jan 2, 2016 at 14:52
  • 1
    @NicolBolas yes. The constraint expressed by the OP was that the f() functions needed to be non-members. He deidn't say that virtuals had to be avoided.
    – Christophe
    Jan 2, 2016 at 14:59
  • 1
    @Christophe exactly, I realize how my code example without virtual functions could have caused confusion but in reality there are virtual functions (otherwise the whole inheritance would be pretty useless IMO).
    – CompuChip
    Jan 2, 2016 at 15:13
0

Here are two possible solutions.


1) Use type-erasure with std::function and avoid inheritance:

class element
{
private:
    std::function<void(element&)> _f;

public:
    template<typename TF>
    element(TF&& f) : _f(std::forward<TF>(f)) { }

    void call_f() { _f(*this); }
};

void print_a(element& e) { std::cout << "a\n"; }    
void print_b(element& e) { std::cout << "b\n"; }

auto make_element_a() { return element{&print_a}; }    
auto make_element_b() { return element{&print_b}; }

int main()
{
    std::vector<element> es;
    es.emplace_back(make_element_a());
    es.emplace_back(make_element_a());
    es.emplace_back(make_element_b());
    es.emplace_back(make_element_a());

    for(auto& e : es) e.call_f();
    // Will print: "a a b a".
}

2) Use the virtual keyword to enable run-time polymorphism:

class element
{
private:
    virtual void f() { }

public:
    void call_f() { _f(*this); }
    virtual ~element() { }
};

void print_a(element& e) { std::cout << "a\n"; }    
void print_b(element& e) { std::cout << "b\n"; }

class a : public element
{
    void f() override { print_a(*this); }
};

class b : public element
{
    void f() override { print_b(*this); }
};

int main()
{
    std::vector<std::unique_ptr<element>> es;
    es.emplace_back(std::make_unique<a>());
    es.emplace_back(std::make_unique<a>());
    es.emplace_back(std::make_unique<b>());
    es.emplace_back(std::make_unique<a>());

    for(auto& e : es) e.call_f();
    // Will print: "a a b a".
}
0

Inheritance is the base class of evil.

By hiding the relationship between these objects in the internal implementation of a handle class, we can create an interface common to all objects even when they are not derived from a common base.

Here's a re-expression of your problem in that vein:

#include <iostream>
#include <memory>
#include <vector>
#include <type_traits>
#include <utility>

class A {};  // note! no inheritance at all
class B {};
class C {};

void f(A& a) { std::cout << "It is an A!\n"; }
void f(B& b) { std::cout << "It is a B\n"; }
void f(C& c) { std::cout << "It is a C!\n"; }

struct fcaller
{
    struct concept
    {
        virtual void call_f() = 0;
        virtual ~concept() = default;
    };

    template<class T>
    struct model final : concept
    {
        model(T&& t) : _t(std::move(t)) {}

        void call_f() override {
            f(_t);
        }
        T _t;
    };

    template<class T, std::enable_if_t<not std::is_base_of<fcaller, std::decay_t<T>>::value>* = nullptr >
    fcaller(T&& t) : _impl(std::make_unique<model<T>>(std::forward<T>(t))) {}

    void call_f()
    {
        _impl->call_f();
    }

private:


    std::unique_ptr<concept> _impl;

};

int main() {
    using namespace std;

    vector<fcaller> v{};
    v.emplace_back(A{});
    v.emplace_back(B{});
    v.emplace_back(C{});

    for(auto& obj : v)
    {
        obj.call_f();
    }

    return 0;
}

Output:

It is an A!
It is a B
It is a C!
2
  • This is somewhat along interesting lines, but you have simply poorly re-implemented std::function. You can drastically simplify and generalize your answer by employing it and a couple lambdas.
    – Puppy
    Jan 2, 2016 at 15:20
  • @Puppy for an interface containing a single method you are correct. If the shared interface gets any bigger that approach does not work. If you have a spare hour, watch this lecture by Sean Parent. It's fascinating and explains why this approach is desirable: channel9.msdn.com/Events/GoingNative/2013/… Jan 2, 2016 at 15:25
0

Thanks for all the great responses guys. The problem seems to have been, that I realized too late (while editing my OP and writing comments to your requests for clarification) I was implementing an existing design pattern. And it turns out I got the pattern backwards.

What I should have done, is create an interface class on top of f that allows me to select another implementation:

class IVisitor 
{ public:
    virtual void visit(const A*) const = 0; 
    virtual void visit(const B*) const = 0; 
    virtual void visit(const C*) const = 0; 
};

// Example implementation: 
class TypePrinter: public IVisitor
{ public:
    // Base* version not needed - yay!
    // virtual void visit(const Base*) const { std::cout << "Called Base :(\n"; }
    virtual void visit(const A* a) const override { cout << "It is an A!\n"; }
    virtual void visit(const B* b) const override { cout << "It is a B\n"; }
    virtual void visit(const C* c) const override { cout << "It is a C!\n"; }
};

Then give Base and all subclasses a method to call visit:

struct A : public Base 
{ public: 
    // This line copied across to `B` and `C` as well:
    virtual void accept(const IVisitor& v) override { v.visit(this); } 
};

And now, as @LogicStuff correctly remarked, polymorphism will nicely solve the overload problem:

TypePrinter visitor;
for(auto& obj : v)
{
    obj->accept(visitor);
}

Look ma, no dynamic_casts! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.