【问题标题】:template function with pqxx results带有 pqxx 结果的模板函数
【发布时间】:2015-12-24 16:30:50
【问题描述】:

这是在 os x yosemite 上,带有来自 clion 中的 xcode 7.2 的 clang。

我正在遍历来自 postgresql 数据库的查询并将结果添加到 json 对象。

for (pqxx::result::const_iterator c = R.begin(); c != R.end(); ++c) {
    participants["participants"] += { \
        {"id", c[0].as<std::string>()},
        {"location", c[1].as<std::string>()},
        {"racename", c[2].as<std::string>()},
        {"racestart_at", c[3].as<std::string>()},
        {"ended_at", static_cast<bool>(c[9].size()) ? c[9].as<std::string>() : ""},
        {"racetime", static_cast<bool>(c[10].size()) ? c[10].as<std::string>() : ""}
    };
}

某些列具有空值,因此我在三元运算符中测试该转换是否为 bool,并返回结果或空字符串。为了使它更简洁,我尝试使用http://www.cprogramming.com/tutorial/templated_functions.html 中的示例添加一个模板函数,并得到了这个:

template <class T>
std::string column_content(T a) {
    return static_cast<bool>(a.size()) ? a.as<std::string>() : "";
}

当我尝试编译程序时出现错误:

Database.cpp:9:44: error: use 'template' keyword to treat 'as' as a dependent template name
return static_cast<bool>(a.size()) ? a.as<std::string>() : "";
                                       ^
                                       template 

我查看了 Cast Chars To Int in Template Functionhttp://www.cplusplus.com/doc/oldtutorial/templates/ 以及来自 google 的其他建议,但看起来我使用了错误的语法,但我无法发现它。

如果我可以使用添加到 json 的模板函数,那么看起来像

{"start_at", column_content(c[8])}

问候 克劳斯

【问题讨论】:

    标签: c++ postgresql templates


    【解决方案1】:

    我暂时把它改成了一个函数。根据http://pqxx.org/devprojects/libpqxx/doc/2.6.9/html/Reference/a00259.html#2a9d36599b217ebfde2cac4633856ac0,传递的类型是pqxx::result::field。

    std::string column_content(pqxx::result::field a) {
        if (static_cast<bool>(a.size())) {
            return a.as<std::string>();
        } else {
            return "";
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      相关资源
      最近更新 更多