【发布时间】:2019-08-07 11:45:26
【问题描述】:
我有一个通用函数来从我的数据库中读取列。它在头文件中的原型是:
template <typename T> void sqlite3_column_template(sqlite3_stmt *stmt, int column, T& value);
这个想法是专门化这个函数来根据值类型调用这些函数:
sqlite3_column_int64(...)
sqlite3_column_double(...)
sqlite3_column_text(...)
在我的cpp 文件中,我编写了这样的专业化函数:
template <> void sqlite3_column_template(sqlite3_stmt *stmt, int column, int& value)
{
value = sqlite3_column_int64(stmt, column);
}
template <> void sqlite3_column_template(sqlite3_stmt *stmt, int column, float& value)
{
value = sqlite3_column_double(stmt, column);
}
template <> void sqlite3_column_template(sqlite3_stmt *stmt, int column, std::string& value)
{
value = reinterpret_cast<const char*>(sqlite3_column_text(stmt, column));
}
我的问题是调用这个函数时的值类型可以是以下几种:
uint32_t, int32_t, int64_t
float, double
我不知道如何判断所有“整数”类型都必须调用函数sqlite3_column_int64。
float 和 double 调用 sqlite3_column_double 函数也是如此。
我该怎么做?有可能吗?
编辑
我使用的解决方案如下:
// the 3 functions in the header file
template <typename T>
std::enable_if_t<std::is_integral_v<T>> sqlite3_column_template(sqlite3_stmt *stmt, int column, T& value)
{
value = sqlite3_column_int64(stmt, column);
}
template <typename T>
std::enable_if_t<std::is_floating_point_v<T>> sqlite3_column_template(sqlite3_stmt *stmt, int column, T& value)
{
value = sqlite3_column_double(stmt, column);
}
template <typename T>
std::enable_if_t<std::is_same_v<T, std::string>> sqlite3_column_template(sqlite3_stmt *stmt, int column, T& value)
{
value = reinterpret_cast<const char*>(sqlite3_column_text(stmt, column));
}
【问题讨论】:
-
你应该看看 SFINAE
标签: c++ function templates c++17 template-specialization