Łukasz Ślusarczyk
Łukasz Ślusarczyk

Reputation: 1864

initialize const member by initializer with output param

There is a function which gives back return value by using pointer to output: MPI_Comm_rank(MPI_Comm comm, int *rank)

There is a class which uses it

struct MyRank
{
  int rank;
  MyRank(MPI_Comm comm) {
    MPI_Comm_rank(comm, &rank);
  }
}

I'd like to elegantly (e.g. by some lambda or other one-liner) make rank to be const field and initialize it on initializer list.

I may write a helper function and use it:

int getRank(MPI_Comm comm) {
  int rank;
  MPI_Comm_rank(comm, &rank);  
  return rank;
}

struct MyRank
{
  int const rank;
  MyRank(MPI_Comm comm) : rank(getRank(comm)) {}
}

But it is 5 lines more. Maybe there is shorter way, e.g by using lambdas. Any ideas?

Upvotes: 0

Views: 37

Answers (1)

Jarod42
Jarod42

Reputation: 217990

You might use lambda directly invoked.

struct MyRank
{
  int const rank;
  MyRank(MPI_Comm comm) : rank([](MPI_Comm comm) {
      int rank;
      MPI_Comm_rank(comm, &rank);  
      return rank;
    }(comm))
  {}
};

Not sure it is more readable though.

Upvotes: 4

Related Questions