Check for value definedness in C++

2020-04-05 12:09发布

I'm working in C++ and I need to know if a scalar value (for instance a double) is "defined" or not. I also need to be able to "undef" it if needed:

class Foo {
public:
    double get_bar();

private:
    double bar;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( undefined(bar) )
        calculate_bar();
    return bar;
}

Is it possible in C++?

Thanks

标签: c++ undef
9条回答
Ridiculous、
2楼-- · 2020-04-05 12:32

As the other answers says, C++ doesn't have this concept. You can easily work around it though.

Either you can have an undefined value which you initialize bar to in the constructor, typically -1.0 or something similar.

If you know that calculate_bar never returns negative values you can implement the undefined function as a check for < 0.0.

A more general solution is having a bool saying whether bar is defined yet that you initialized to false in the constructor and when you first set it you change it to true. boost::optional does this in an elegant templated way.

This is what the code example you have would look like.

class Foo {
public:
    double get_bar();
    Foo() : barDefined(false) {}
private:
    double bar;
    bool barDefined;
    void calculate_bar() {
        bar = something();
    }
};

double Foo::get_bar() {
    if ( barDefined == false ) {
        calculate_bar();
        barDefined = true;
    }
    return bar;
}
查看更多
贪生不怕死
3楼-- · 2020-04-05 12:36

You must do it by using an extra boolean.

To implement using an extra boolean, you could try logic like the following template:

template<typename T>
struct Defined
{
 bool defined;
 T value;
 Defined() : defined(false) {}
 Defined(const T& value_) : defined(true), value(value_) {}
 ... and perhaps other operators here ...
 ... to make this behave even more like a T ...
};
查看更多
祖国的老花朵
4楼-- · 2020-04-05 12:37

You could try the Construct on first use idiom and write get_bar() this way:

double & get_bar()
{
    static double *bar = new double(something());
    return *bar;
}

When you call get_bar() it will make bar for you if no one has asked for it yet. Any subsequent calls will just return bar. As the linked page says, this doesn't technically leak memory because the OS will reclaim it when the program exits.

UPDATE:

Changed the return value to double & to allow you to modify bar.

查看更多
登录 后发表回答