jeudi 24 janvier 2019

Overloading an enum in a child class in c++

I'm interested in defining a general class to be inherited that operates differently based on an enum and map of that enum to some data structure.

In the following code I have test_child inherit from test_parent, which has the shared functions already implemented. My plan would be to have many classes inherit from a class like parent_class, but to define a unique 'field' enum and corresponding 'mapping' map.

#include <iostream>
#include <string>
#include <unordered_map>

class test_parent {
public:
    enum class field {
        A,
        B,
        C
    };

    typedef struct {
        std::string s;
        int i, j;
    } data_t;

    std::unordered_map<field, data_t> mapping {
        {field::A, {"A", 1, 1}},
        {field::B, {"B", 2, 2}},
        {field::C, {"C", 3, 3}}
    };

    int get_i (field f) {
        return mapping[f].i;
    }

    std::string get_s (field f) {
        return mapping[f].s;
    }   
};

class test_child : test_parent {
public:
    enum class field {
        D,
        E
    };

    std::unordered_map<field, data_t> mapping {
        {field::D, {"D", 4, 4}},
        {field::E, {"E", 5, 5}}
    };
};

int main () {
    test_parent tp;
    test_child tc;

    std::cout << tp.get_i(test_parent::field::A) << " " << tc.get_i(test_child::field::E) << std::endl;

    return 0;
}

This code returns a compilation error:

test.cpp: In function ‘int main()’:
test.cpp:55:86: error: no matching function for call to ‘test_child::get_i(test_child::field)’
std::cout << tp.get_i(test_parent::field::A) << " " << tc.get_i(test_child::field::E) << std::endl;
                                                                                    ^
test.cpp:28:6: note: candidate: int test_parent::get_i(test_parent::field)
int get_i (field f) {
    ^~~~~
test.cpp:28:6: note:   no known conversion for argument 1 from ‘test_child::field’ to ‘test_parent::field’

But What I expect to be printed is:

1 5

Aucun commentaire:

Enregistrer un commentaire