对于熟悉 Oracle 模板库 (OTL)、boost::any 和 Loki 库(现代 C++ 设计中描述的库)的人,这里是概念证明 TMP 代码,使您能够存储一行 otl_stream在vector<boost::any> 容器中并按列号访问数据。 '是的',我将把它合并到生产代码中。
#include <iostream>
#include <vector>
#include <string>
#include <Loki/Typelist.h>
#include <Loki/TypeTraits.h>
#include <Loki/TypeManip.h>
#include <boost/any.hpp>
#define OTL_ORA10G_R2
#define OTL_ORA_UTF8
#include <otlv4.h>
using namespace Loki;
/* Auxiliary structs */
template <int T1, int T2>
struct IsIntTemplateEqualsTo{
static const int value = ( T1 == T2 );
};
template <int T1>
struct ZeroIntTemplateWorkaround{
static const int value = ( 0 == T1? 1 : T1 );
};
/* Wrapper class for data row */
template <class TList>
class T_DataRow;
template <>
class T_DataRow<NullType>{
protected:
std::vector<boost::any> _data;
public:
void Populate( otl_stream& ){};
};
/* Note the inheritance trick that enables to traverse Typelist */
template <class T, class U>
class T_DataRow< Typelist<T, U> >:public T_DataRow<U>{
public:
void Populate( otl_stream& aInputStream ){
T value;
aInputStream >> value;
boost::any anyValue = value;
_data.push_back( anyValue );
T_DataRow<U>::Populate( aInputStream );
}
template <int TIdx>
/* return type */
Select<
IsIntTemplateEqualsTo<TIdx, 0>::value,
typename T,
typename TL::TypeAt<
U,
ZeroIntTemplateWorkaround<TIdx>::value - 1
>::Result
>::Result
/* sig */
GetValue(){
/* body */
return boost::any_cast<
Select<
IsIntTemplateEqualsTo<TIdx, 0>::value,
typename T,
typename TL::TypeAt<
U,
ZeroIntTemplateWorkaround<TIdx>::value - 1
>::Result
>::Result
>( _data[ TIdx ] );
}
};
int main(int argc, char* argv[])
{
db.rlogon( "AMONRAWMS/WMS@amohpadb.world" ); // connect to Oracle
std::cout<<"Connected to oracle DB"<<std::endl;
otl_stream o( 1, "select * from blockstatuslist", db );
T_DataRow< TYPELIST_3( int, int, std::string )> c;
c.Populate( o );
typedef enum{ rcnum, id, name } e_fields;
/* After declaring enum you can actually acess columns by name */
std::cout << c.GetValue<rcnum>() << std::endl;
std::cout << c.GetValue<id>() << std::endl;
std::cout << c.GetValue<name>() << std::endl;
return 0;
};
对于那些不熟悉上述库的人。
OTL 的 otl_stream 容器的问题在于,通过声明适当类型的变量并将operator >> 应用到 otl_stream 对象,只能按顺序访问列数据:
otl_stream o( 1, "select * from blockstatuslist", db );
int rcnum;
int id;
std::string name;
o >> rcnum >> id >> name;
这并不总是很方便。解决方法是编写一些包装类并使用来自 otl_stream 的数据填充它。希望能够声明列类型列表,然后:
- 取列的类型T
- 声明该类型的变量
- 申请
olt_stream::operator >>(T&)
- 存储结果(在 boost::any 的向量中)
- 取下一列的类型并重复,直到处理完所有列
您可以在 Loki 的 Typelist 结构、模板特化和继承的帮助下完成所有这些工作。
借助 Loki 的库结构,您还可以生成一堆 GetValue 函数,这些函数返回适当类型的值,从列号(实际上是 Typelist 中的类型数)推导出来。