Search code examples
c++initializer-list

C++ how to check a condition before using initialiser list?


I am writing a piece of code that is structured this way:

//field.h
class Field {
    std::vector<std::vector<double>> data;

    public:
    Field(int, int);        
};
Field::Field (int dim0, int dim1) :: data(dim0, std::vector<double>(dim1, 0)) { }

Then I am using this Field in another class like:

//approx.h
class Field;
class Approx {
    Field SWAP;

    public:
    Approx(int, int);
};
Approx::Approx (int size, int dim) { }
/*I want to initialise SWAP like this:
     if (size > dim) SWAP(size, dim)
     else SWAP(dim, size)
*/

I do not know how to do this. I presume it is impossible without initialiser lists? Can I even ask inside initialiser list these questions?

If there is another way to do so, I'd be grateful for any type of solution.


Solution

  • There are a couple ways to solve this. First, you could just use std::min and std::max to get the right values like

    Approx::Approx (int size, int dim) : SWAP(std::max(dim, size), std::min(dim, size)) {}
    

    Secondly, you could write a lambda and immediately invoke it like

    Approx::Approx (int size, int dim) : SWAP([](auto size, auto dim){ if (size > dim) return Field(size, dim); else return Field(dim, size); }(size, dim)) {}
    

    If you don't like having the code in the initialization list then you can out it into a private static function and call the function instead.