通过加入assigned字段来判断是否需要更新数据库字段
field.h
#ifndef _FIELD_H_
#define _FIELD_H_
#include <sdbus/variant.h>
#define SETIFASSIGNED(A, B) \
if (B.assigned()) { \
A = B; \
} \
template<class T>
class Field
{
public:
Field() : assigned_(false) {}
Field(const Field<T>& rhs) : value_(rhs.value_), assigned_(false) {}
Field(const T& value) : value_(value), assigned_(false) {}
Field& operator= (const Field<T>& rhs) {value_ = rhs.value_; assigned_ = true; return *this;}
Field& operator= (const T& value) {value_ = value; assigned_ = true; return *this;}
operator T () {return value_;}
operator const T() const {return value_;}
const T& ref() const {return value_;}
bool assigned() const {return assigned_;}
T value() {return value_;}
private:
T value_;
bool assigned_;
};
void GetFieldString(const sdbus::VariantMap& mp, int fid, Field<std::string>& field);
void GetFieldInt(const sdbus::VariantMap& mp, int fid, Field<int>& field);
void GetFieldDouble(const sdbus::VariantMap& mp, int fid, Field<double>& field);
void GetFieldBool(const sdbus::VariantMap& mp, int fid, Field<bool>& field);
#endif
filed.cpp
#include "field.h"
void GetFieldString(const sdbus::VariantMap& mp, int fid, Field<std::string>& field)
{
std::string val;
if (mp.GetString(fid, val)) {
field = val;
}
}
void GetFieldInt(const sdbus::VariantMap& mp, int fid, Field<int>& field)
{
int val;
if (mp.GetInt32(fid, val)) {
field = val;
}
}
void GetFieldDouble(const sdbus::VariantMap& mp, int fid, Field<double>& field)
{
double val;
if (mp.GetDouble(fid, val)) {
field = val;
}
}
void GetFieldBool(const sdbus::VariantMap& mp, int fid, Field<bool>& field)
{
bool val;
if (mp.GetBool(fid, val)) {
field = val;
}
}
使用方式:
classQuote
{
public:
Quote() : {}
public:
Field<std::string> id_;
Field<std::string> protocol_id_;
......
}
赋值:
GetFieldString(mp,FID_ID, quote->id_);
读取:
if(quote->protocol_id_.assigned())
{
INSERT_STRING_FIELD(protocol_id, quote->protocol_id_.value());
}
if(quote->*.assigned())
{
INSERT_STRING_FIELD(*,quote->*.value());
}
优势举例:
更新数据库某些字段,可以统一提供一个接口即可。