gpt4 book ai didi

c++ - 使用可变参数模板和 boost 将表映射到 map

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:53:45 26 4
gpt4 key购买 nike

我试图在 map 中复制一个数据库表,其中它的主键将是 map 的键,其余列是 boost:vector 的实例。我是 boost 和可变参数模板的新手。我曾尝试编写一个包装器,但它仅适用于固定数量的列。以下是代码

#include <boost/container/vector.hpp>
#include <iostream>
#include <string>
#include <map>
#include <type_traits>

typedef boost::container::vector<std::string> MAPPED_COLS;
typedef std::map <int, MAPPED_COLS > TABLE ;
typedef std::map <int, MAPPED_COLS > ::iterator ROW_ITER;

typedef std::string str;

template <typename str>
class MappedTable
{
private:
TABLE mapTable;
MAPPED_COLS cols;
ROW_ITER row;

std::string scTableName;
int iRows;
int iCols;
public:
MappedTable() { iCols=3; }

MappedTable(int iNumCols) { iCols=iNumCols;}
~MappedTable() { }

template <str>
void fnRowCols() //termination version
{
}

template <str>
void fnCols(const str& scCol2, const str& scCol3,...)
{
if(cols.size()>=iCols)
{
cols.erase (cols.begin(),cols.begin()+iCols);
}
cols.push_back(scCol2);

fnCols(scCol3,...);
}

template <str>
void fnMapRow(int iCol1,const str& scCol2,...)
{
fnCols(scCol2,...);
mapTable[iCol1]=MAPPED_COLS(cols);
}


MAPPED_COLS& fnGetRow(int iFindKey)
{
row=mapTable.find(iFindKey);
if(row!=mapTable.end())
return (row->second);
}
};

以下是上述包装器的 main(),如果我没有在我的包装器中使用可变参数模板,它可以正常工作:-

 int main()
{
MappedTable Table(3) ;

std::string vid[]={"11", "21", "51", "41"};
std::string fare[]={"100", "400", "200", "4000"};
std::string vehicle[]={"bus", "car", "train", "aeroplane"};

int i=0;

for(i=0;i<4;i++)
{
Table.fnMapRow(i,vid[i],fare[i],vehicle[i]);
}

for(i=0;i<4;i++)
{
MAPPED_COLS mpCol=Table.fnGetRow(i);
std::cout<<"\n "<<i<<" "<<mpCol[0]<<" "<<mpCol[1]<<" "<<mpCol[2];
}

std::cout<<"\n";

return 0;
}

代码是使用 Boost 1.51.0 和 gcc 4.4 编译的,带有 std=c++0x 选项

谁能告诉我我缺少的是什么?我对更好的想法持开放态度,并且很想知道即使效率不够高,这个特定示例将如何工作。

我在下面的回答中提供了工作代码片段(感谢 Rost)。如果有人能提出一些更好、更多的方法来将整个表存储到 map 中,那就太好了。

谢谢!!

最佳答案

您的可变参数模板函数语法看起来不正确。它应该是这样的:

 template <typename... VarArgs>
void fnCols(const str& scCol2, const str& scCol3, const VarArgs&... args)
{
// Non-relevant code skipped
fnCols(scCol3, args...); // Recursive call with expanding arguments pack
}

fnMapRow 类似的问题.还有 template <str>在模板成员函数定义之前不需要。

关于c++ - 使用可变参数模板和 boost 将表映射到 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12977291/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com