下面给出的是我正在尝试编译的代码(其中的 CPP 部分)
template<typename... T>
void SelectOperation::fetchNextRow(tuple<T...>& row) const
{
fetchColumn<0, decltype(row), T...>(row, nullptr);
}
template<int index, typename T, typename U>
void SelectOperation::fetchColumn(T& row) const
{
cout << typeid(row).name();
std::get<index>(row) = this->get<U>(index + 1);
}
template<int index, typename T, typename U, typename... V>
void SelectOperation::fetchColumn(T& row, void*) const
{
fetchColumn<index, T, U>(row);
fetchColumn<index + 1, T, V...>(row, nullptr); //Error at this statement
}
我得到的错误如下:
D:\workspaces\Calzone_Mayank\modules\Figgy\include\common/db/core/SelectOperation.h(149):
error C2783: 'void figgy::SelectOperation::fetchColumn(T &,void *) const': could not deduce
template argument for 'U'
D:\workspaces\Calzone_Mayank\modules\Figgy\include\common/db/core/SelectOperation.h(58):
note: see declaration of 'figgy::SelectOperation::fetchColumn'
D:\workspaces\Calzone_Mayank\modules\Figgy\include\common/db/core/SelectOperation.h(149):
error C2780: 'void figgy::SelectOperation::fetchColumn(T &) const': expects 1 arguments
- 2 provided
我不明白为什么不能推导出'U'的参数
。为什么编译器无法确定它应该查找哪个重载函数?
编辑
fetchNextRow 的调用如下所示:
template<typename... T>
void SelectOperation::fetchAllRows(vector<tuple<T...>>& rows) const
{
while (next())
{
tuple<T...> row;
fetchNextRow<T...>(row);
rows.push_back(row);
}
}
和
vector<tuple<string, string, int>> rows;
SelectOperation o("users", {"name", "employee_id", "age"});
o.fetchAllRows<string, string, int>(rows);
最佳答案
考虑一下:
template<int index, typename T, typename U, typename... V>
void SelectOperation::fetchColumn(T& row, void*) const {
fetchColumn<index, T, U>(row);
fetchColumn<index + 1, T, V...>(row, nullptr); //Error at this statement
}
当V...
为空参数包时,它将不起作用。
您使用两个参数(row
和 nullptr
)调用了 fetchColumn
,因此递归调用了上述函数。
每次使用参数包中的类型(即 U
)时。
迟早,V...
将是一个空参数包,因此您不会有任何 U
并且编译器说它既无法找到它也不能推断它。
您应该提供两个函数,递归函数和最后一个函数。
例如:
template<int index, typename T, typename U, typename... V>
void SelectOperation::fetchColumn(T& row, void*) const {
fetchColumn<index, T, U>(row);
fetchColumn<index + 1, T, V...>(row, nullptr); //Error at this statement
}
template<int index, typename T>
void SelectOperation::fetchColumn(T& row, void*) const {
// Do whatever you want with your last type...
}
关于C++ Variadic 模板 - 无法找出编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39784204/