Initializing from a pair in constructur intializer list

108 Views Asked by At

I have a function f returning a pair of objects of classes A and B:

auto f() -> std::pair<A,B>;

Furthermore, I have a class C that has A and B as members:

class C {
  public:
    C();
  private:
    A a;
    B b;
};

In the constructor of C, I want to use the member initalizer list and initialize with the output of f:

C(): a(f().first), b(f().second) {}

This calls f twice though and it is a quite complicated function. Is there a way to achieve this using the member-initializer list without calling f twice? The internal structure of C can unfortunately not be changed.

2

There are 2 best solutions below

2
HolyBlackCat On BEST ANSWER

Improving on the idea from AnkitKumar's answer:

class C
{
    A a;
    B b;
    
    C(std::pair<A,B> &&pair) : a(std::move(pair.first)), b(std::move(pair.second)) {}

  public:
    C() : C(f()) {}
};
4
Ankit Kumar On

One possible solution:

class C {
  public:
    C(std::pair<A,B>);
  private:
    ...
};

C(pair<A,B> p): a(p.first), b(p.second) {}

You'll now call f only once, which will work so long as it doesn't contradict some other requirements.