0

I'm trying to write a layer for making some components of a project more modular. How can I make a class Foo exactly equal to a class Bar, where Foo would be able to be used as the variable 'a' in a function int testFunc(Bar a)?

Would the only solution be to have Foo have a definition like this?

class Foo {
public:
    Foo(int a) : barReturn(a) {};
    operator Bar() const { return barReturn; }
private:
    Bar barReturn;
};
  • It depends on what you expect `testFunc()` to do when passed a `Foo` - and you haven't specified that at all. There are many options - all with pros and cons. One is to keep `Foo` and `Bar` completely independent, and provide a `testFunc(Foo)` overload that creates a `Bar` from the `Foo`, and passes it to `testFunc(Bar)` (`testFunc(Bar)` then doesn't need to know anything about `Foo`). Another option is `using Foo = Bar` which makes `Foo` an alternative name for `Bar`. Other options include inheritance (e.g. `Foo` inherits from `Bar` and overrides inherited virtual functions) – Peter Apr 19 '20 at 08:00

2 Answers2

1

If you want a true alias, you might do an alias:

since C++11:

using Foo = Bar;

or the old way (still valid):

typedef Bar Foo;
Jarod42
  • 203,559
  • 14
  • 181
  • 302
0

May be you can use the polymorphism of c++.There are some diffrent components derived an interface Foo.

class Foo {
public:
    virtual Foo(int a);
    virtual Update(int a);
};

class Bar1 : public Foo{
public:
    virtual Bar1(int a): m_a(a);
    virtual Update(){
        // TODO:
    }
private:
    int m_a;
};

class Bar2 : public Foo{
public:
    virtual Bar1(int a): m_b(a);
    virtual Update(){
        // TODO:
    }
private:
    int m_b;
};

// There a module to do Foo
void ProcessModule(){
    std::vector<Foo*> v;
    v.push_back(new Bar1(1));
    v.push_back(new Bar2(2));

    for (std::vector<Foo*>::itreator it = v.begin(); v != v.end(); ++v){
        it->UPdate()
    }
}
上山老人
  • 412
  • 4
  • 12
  • The example function prototype is `int testFunc(Bar a)`, so 1) The goal is to stick a `foo` into a a `bar`. You seem to have this the other way around. 2) [Object Slicing](https://stackoverflow.com/questions/274626/what-is-object-slicing) would make a mess of using inheritance here. – user4581301 Apr 19 '20 at 06:21
  • @user4581301 I thought may be inheritance may slove the problem of this need "I'm trying to write a layer for making some components of a project more modular." If the goal is to stick a foo into a bar, he need use the pointer, not a object. – 上山老人 Apr 20 '20 at 03:41