![](/img/trans.png)
[英]pqxx::result::tuple has not been declared (PostgreSQL library for c++)
[英]PostgreSQL C++ (pqxx) and setting value if not NULL
我有一些看起來像這樣的代碼:
for (const auto& query_result_row : query_result) {
my_struct.a = query_results_row["a"].as<int>();
my_struct.b = query_results_row["b"].as<string>();
// and so forth.
}
一般來說,可能有很多不同類型的字段。 這很好,但是如果選定的字段是 NULL,這將引發異常。 所以我現在寫了這個,這很尷尬,而且很容易出錯:
for (const auto& query_result_row : query_result) {
if (!query_results_row["a"].is_null()) {
my_struct.a = query_results_row["a"].as<int>();
}
if (!query_results_row["ab"].is_null()) {
my_struct.b = query_results_row["b"].as<string>();
}
// and so forth.
}
伊克。
也許,我想,我可以制作一個(模板化的)function 來簡化這一點:
for (const auto& query_result_row : query_result) {
MaybeSet(my_struct.a, query_results_row["a"]);
MaybeSet(my_struct.b, query_results_row["b"]);
// and so forth.
}
這里的問題是query_results_row["a"]
本身就是一個模板類型,而且, as()
類型可能與my_struct
類型不完全相同(例如,不同類型的整數),雖然我不今天看到它,這聞起來像是某天可能導致意外演員表的那種東西。
// Doesn't work.
template <typename valueT, typename postgresFieldT>
void MaybeSet(valueT& my_struct_field, const postgresFieldT& field) {
if (!field.is_null()) {
my_struct_field = field.as<valueT>();
}
}
如果它們不是 null 但不嘗試的話,有什么建議可以更簡潔地表達設置事物的想法嗎?
對於后代:我稍微改變了問題,因此得出了一個簡單的解決方案。
template <typename T>
class SetThing {
// ...
void MaybeSet(const pqxx::result::field& field) {
if (!field.is_null()) {
SetClean(field.as<T>());
}
}
template <typename asT>
void MaybeSet(const pqxx::result::field& field) {
if (!field.is_null()) {
SetClean(field.as<asT>());
}
}
// ...
}
用法然后變成
SetThing thing;
thing.MaybeSet(query_result_row["dog"]);
thing.MaybeSet<the_cast_type>(query_result_row["complicated"]);
第二種形式用於少數復雜類型(例如,類),我可以從簡單的東西(例如,int 或字符串)構造它們,但它不是SetThing
的基本(模板化)類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.