Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
717 views
in Technique[技术] by (71.8m points)

data access layer - Nullable values in C++

I'm creating a database access layer in native C++, and I'm looking at ways to support NULL values. Here is what I have so far:

class CNullValue
{
public:
    static CNullValue Null()
    {
        static CNullValue nv;

        return nv;
    }
};

template<class T>
class CNullableT
{
public:
    CNullableT(CNullValue &v) : m_Value(T()), m_IsNull(true)
    {
    }

    CNullableT(T value) : m_Value(value), m_IsNull(false)
    {
    }

    bool IsNull()
    {
        return m_IsNull;
    }

    T GetValue()
    {
        return m_Value;
    }

private:
    T m_Value;
    bool m_IsNull;
};

This is how I'll have to define functions:

void StoredProc(int i, CNullableT<int> j)
{
    ...connect to database
    ...if j.IsNull pass null to database etc
}

And I call it like this:

sp.StoredProc(1, 2);

or

sp.StoredProc(3, CNullValue::Null());

I was just wondering if there was a better way than this. In particular I don't like the singleton-like object of CNullValue with the statics. I'd prefer to just do

sp.StoredProc(3, CNullValue);

or something similar. How do others solve this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Boost.Optional probably does what you need.

boost::none takes the place of your CNullValue::Null(). Since it's a value rather than a member function call, you can do using boost::none; if you like, for brevity. It has a conversion to bool instead of IsNull, and operator* instead of GetValue, so you'd do:

void writeToDB(boost::optional<int> optional_int) {
    if (optional_int) {
        pass *optional_int to database;
    } else {
        pass null to database;
    }
}

But what you've come up with is essentially the same design, I think.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...