vendredi 20 décembre 2019

using overloaded functions with polymorphic behaviour

I am implementing a generic work engine class that executes field-specific tasks. All fields shall be derived from a base class so polymorphic behavior will be used. I created overloaded functions with type-specific to derived fields, i.e work_engine::run(const a_field& af) in the below code. I've assumed whenever a field comes (the base class type), the appropriate function will be called automatically. However, I have got the error below (refers // magic line):

Error   C2664    'void work_engine::run(const b_field &)': cannot convert argument 1 from 'base_field' to 'const a_field &' 

I used to use this approach in C#, but I am not familiar with it in C++. By using C++11 and later features, I would like to implement the same approach, as it is cleaner code than using if-else statements with cast operations. On the other hand, perhaps I am doing primitive mistakes, so I'd like to separate my questions into two items:

  1. What is the proper way of achieving my intention?
  2. What is the origin of the error I've met?

Thanks in advance for all your comments,

Header1.h including class definitions is below:

#pragma once
#include <algorithm>
#include <list>

// abstract class of all fields 
class base_field
{
public:
    base_field() {}
    virtual ~base_field() {}
};

// custom a field
class a_field : public base_field
{
public:
    a_field() : base_field(){}
};

// custom b field
class b_field : public base_field
{
public:
    b_field() : base_field() {}
};

class work_engine
{
public:
    std::list<base_field> fields;
private:
    void run(const a_field& af) {}
    void run(const b_field& bf){}
public:
    void run_all()
    {
        for_each(fields.begin(), fields.end(), [&](auto& el) { this->run(el); }); // magic line
    }
};

An the main below:

#include <iostream>
#include <Header1.h>

int main()
{
    work_engine engine;
    engine.fields.push_back(a_field());
    engine.fields.push_back(b_field());
    engine.run_all();
}

Aucun commentaire:

Enregistrer un commentaire