C ++中的可空值 [英] Nullable values in C++
问题描述
我在本机C ++中创建数据库访问层,我正在寻找支持NULL值的方法。这是我到目前为止:
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
}
我这样调用: p>
And I call it like this:
sp.StoredProc(1, 2);
或
sp.StoredProc(3, CNullValue::Null());
我只是想知道有没有比这更好的方法。特别是我不喜欢CNullValue的单例对象与静态。
我只想做
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?
推荐答案
Boost.Optional 可能会满足您的需要。
Boost.Optional probably does what you need.
boost :: none
替换您的 CNullValue :: Null()
。因为它是一个值,而不是一个成员函数调用,你可以使用boost :: none; 如果你喜欢,为了简洁,可以做。它转换为
bool
,而不是 IsNull
和运算符*
而不是 GetValue
,所以你会这样做:
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.
这篇关于C ++中的可空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!