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"));
C++ 11 可变参数模板和 boost::any 实现可变参数函数,布布扣,bubuko.com
C++ 11 可变参数模板和 boost::any 实现可变参数函数
原文地址:http://www.cnblogs.com/sylar1513/p/3850075.html