Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a possibility to use std::vector<T> as parameter in this case

Tags:

c++

Consider the following:

struct A
{
    std::string name;
    // other members
};

struct B
{
    std::string name;
    // different members
};

class Table
{
private:
    std::vector<A> vec1;
    std::vector<B> vec2;
};

What would be the correct way to have:

int Foo(const std::vector<T> &param, bool isB)
{
};

where the actual call will be:

auto result = Foo( vec1, false );

or

auto result = Foo( vec2, true );

and then Foo() will proceed based on the isB flag?

Or there is a better way?

like image 216
Igor Avatar asked Dec 02 '25 21:12

Igor


1 Answers

Seems simple:

int Foo(const std::vector<A>&) {
// whatever
}

int Foo(const std::vector<B>&) {
// whatever
}

And if there's lots of common code between the two, just put that into its own function:

template <class T> int Foo_helper(const std::vector<T>&) {
// whatever
}

The underlying issue is that A and B are two different types, and you can't write a single function that takes two different types. That's what templates do.

like image 88
Pete Becker Avatar answered Dec 05 '25 12:12

Pete Becker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!