C++ Variadic 模板 - 无法找出编译错误

标签 c++ c++11 compiler-errors variadic-templates

下面给出的是我正在尝试编译的代码(其中的 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... 为空参数包时,它将不起作用。
您使用两个参数(rownullptr)调用了 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/

相关文章:

c++ - 确定 QImage 的哪些像素在使用 QPainter 绘画时发生了变化

c++ - 函数模板的非最后默认模板参数

c++ - 我想返回局部变量的地址

c++ - 转换为 `const Y` 不适用于 clang 上的 `R&&`

c++ - 分离的 std::thread 终止后是否需要删除?

c++ - VS2017从15.4.1升级到15.5.1导致构建错误

iphone - 错误: expected specifier-qualifier-list before 'SearchViewController'

c++ - 如何处理mfc中同一个按钮的单击和双击?

c++ - 带有指向成员函数指针的地址运算符

c++ - endl 和 '\n' 之间的区别以及它们与刷新输出缓冲区的关系?