mardi 30 août 2016

Function with multiple return types

I have two enums which basically determine (on runtime) what to do. The 'mapping' looks something like

struct Foo { class CA; class CB; class CC; CA a; CB b; CC c; };
enum Base { A, B, C };
enum Func { X, Y };
Foo foo;

// A, X => use(foo.a.x());
// A, Y => use(foo.a.y());
// B, X => use(foo.b.x());
// B, Y => use(foo.b.y());

The problem is, that a, b and C, as well as the return types of x() and y() are all of different types (some really huge template types).

Mapping the two enums using switches or ifs is pretty ugly and requires lots of effort so I wondered, if I could somehow write something like this:

struct Foo { class CA; class CB; class CC; CA a; CB b; CC c; };
enum Base { A, B, C, };
enum Func { X, Y, }; 

template <typename T> auto applyFunc(Func f, T t)
{
    switch(f)
    {
        case Func::X: return t.x();
        case Func::Y: return t.y();
    }
}


auto getBase(Base b, Foo f)
{
    switch(bt)
    {
        case BaseType::A: return f.a;
        case BaseType::B: return f.b;
        case BaseType::C: return f.c;
    }
}


Func f;
Base b;
Foo foo;

use(applyFunc(f, getBase(b, foo)));

Aucun commentaire:

Enregistrer un commentaire