Search code examples
c++c++11expression-evaluation

How avoid error on not evaluated code C++?


Apologies for the most ambiguous and bizarre title.
Suppose we have 2 classes A and B.
class B has interface hasSmth but class A has not.
How to make this code evaluate without compile errors?

class A {
    //..implementation
    int id() { return 1; }
};

class B {
    //..implementation
    int id() { return 2; }
    bool hasSmth() { return true; }
};

int main() 
{
    auto obj = someFunction();//returns A or B
    if (obj.id() == 1 || (obj.id() == 2 && obj.hasSmth())) {
        ...
    }
}

If the function returns obj of type B, then we are good.
But if it returns obj of type A, compiler will complain about A not having hasSmth, regardless of that part of if never been evaluated.

Can someone give a workaround please?


Solution

  • Can someone give a workaround please?

    Read the declaration of someFunction to see what it returns. In the case it doesn't return B, then don't write obj.hasSmth(). Problem solved.

    Now, let's change the question a bit. Let's say that you want to make this work without knowing the return type. Perhaps because rather than main you may be actually writing a template that works with different types. There are several approaches, but function overloads are a simple one:

    bool check([[maybe_unused]] const A&) {
        return true;
    }
    
    bool check(const B& b) {
        return b.hasSmth();
    }
    
    template<bool returnsA>
    void foo() {
        auto obj = someTemplate<returnsA>(); // returns A or B
        if (check(obj)) {