gartenriese
gartenriese

Reputation: 4366

conversion operator with const

I have the following class:

class A {
     B m_data;
};

Also I have a function which needs B& as an argument.

How do I implement a conversion operator that can cast from const A& to B&?

I tried the following (derived from here):

operator B() const { return m_data; }

But that does not work, it says "no matching function call" when I want to call the function which needs B&.

EDIT: To clarify for what I am doing this: I use OpenCV and have implemented a Image class which is a wrapper for cv::Mat. I want to call cv::calcOpticalFlowSF which takes cv::Mat& as input and I have a const Image&.

EDIT2: It should look like this:

const Image OpticalFlowSF::getFlowImage(const Image & in1, const Image & in2) {
    Image flow;
    cv::calcOpticalFlowSF(in1, in2, flow, m_layers, m_averagingBlockSize, m_maxFlow);
    return flow;
}

Upvotes: 0

Views: 2233

Answers (1)

Jarod42
Jarod42

Reputation: 218343

You can't (safely) returning B& from const A (you may use a const_cast...)
You can returning B& from A and/or const B& from const A.

class A {
public:
    /* explicit */ operator const B&() const { return m_data; }
    /* explicit */ operator B&() { return m_data; }

    // Avoid that
    // operator B&() const { return const_cast<A*>(this)->m_data; }

    // simple getter.
    const B& getB() const { return m_data; }
    B& getB() { return m_data; }

private:
     B m_data;
};

BTW, a simpler getter seems more appropriate in most case.

You may use it that way:

A a;

B& b1 = a; // would not work if uncomment the explicit keyword.
B& b2 = a.getB();
B& b3 = statitc_cast<B&>(a);

Upvotes: 3

Related Questions