C++ 11 可变参数模板和 boost::any 实现可变参数函数

 1 class SqlHelper
 2 {
 3 public:
 4     template <typename... Params>
 5     static bool preparedExecute(sql::PreparedStatement* pstmt, Params... parameters)
 6     {
 7         return doPreparedExecute(pstmt, 1, parameters...);
 8     }
 9 
10 private:
11     template <typename... Params>
12     static bool doPreparedExecute(sql::PreparedStatement* pstmt, int i, boost::any value, Params... parameters)
13     {
14         setAnyType(pstmt, i, value);
15         return doPreparedExecute(pstmt, ++i, parameters...);
16     }
17 
18     static bool doPreparedExecute(sql::PreparedStatement* pstmt, int i, boost::any value)
19     {
20         assert(pstmt != nullptr);
21         setAnyType(pstmt, i, value);
22         return pstmt->execute();
23     }
24 
25     static void setAnyType(sql::PreparedStatement* pstmt, int i, boost::any value)
26     {
27         assert(pstmt != nullptr);
28 
29         if (value.type() == typeid(int32_t))
30         {
31             pstmt->setInt(i, boost::any_cast<int32_t>(value));
32         }
33         else if (value.type() == typeid(std::string))
34         {
35             pstmt->setString(i, boost::any_cast<std::string>(value));
36         }
37         else if (value.type() == typeid(char const *))
38         {
39             pstmt->setString(i, boost::any_cast<char const *>(value));
40         }
41 
42         // ......
43     }
44 };

其实就是在模板实例化的时候递归实例化

调用方法

1 SqlHelper::preparedExecute(pstmt.get(), "1", 1u, 1f, 1.0, std::string("1"));
2 SqlHelper::preparedExecute(pstmt.get(), 1.0, "1", 1f, 1u, std::string("1"), std::string("2"));

转载于:https://www.cnblogs.com/sylar1513/p/3850075.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值