synaptik
synaptik

Reputation: 9529

C++ class interface to pass-through to another member variable

Let's say I have a class Param defined like this:

class Param {
public:
    std::vector<double> lb;
    std::vector<double> mid;
    std::vector<double> ub;
    int level;
};

The purpose of this class is to define lower- and upper-bounds (lb and ub, respectively) and a midpoint estimate for different parameters. Assume that for a given object, lb, mid, and ub have the same number of elements.

Now, if level<0, I want to use the lb estimates. If level==0, I want to use the mid estimates. Otherwise (if level>0), I want to use the ub estimates.

My question is: how can I create a single member function (or something akin to a reference member variable) that will automatically "pass through" to the appropriate member std::vector<double> based on the value of level?

For example, if I have a function

void f(const std::vector<double>& X);

or

void g(std::vector<double>& X);

I want to be able to do something like this:

Param myParam;
// set values of myParam.lb, myParam.mid, and myParam.ub, and myParam.level
f(myParam.__?__);
g(myParam.__?__);

Upvotes: 2

Views: 471

Answers (2)

Potatoswatter
Potatoswatter

Reputation: 137920

Quite simple.

std::vector< double > & getBound() {
    if ( level < 0 ) return lb;
    if ( level == 0 ) return mid;
    return ub;
}

Add a const overload returning a const & reference if necessary.

I would recommend against doing anything trickier than this. If you want to get something from an object, mentioning a function is usually better than defining a function which is automatically called despite not being named.

(Note: I submitted this more than three hours ago, but connection difficulties delayed it, hence the redundancy.)

Upvotes: 0

paddy
paddy

Reputation: 63481

You can add cast operators to your class:

class Param {
    //...

    operator std::vector<double>& () {
        if( level < 0 ) return lb;
        if( level > 0 ) return ub;
        return mid;
    }

    operator const std::vector<double>& () const {
        if( level < 0 ) return lb;
        if( level > 0 ) return ub;
        return mid;
    }
};

Now you can call like this:

f(myParam);
g(myParam);

Upvotes: 2

Related Questions