创建通用插入功能

时间:2017-03-11 11:02:03

标签: c++ templates c++14 variadic-templates variadic

我试图创建可以获取表名和值并将插入返回到查询中的泛型函数,并提出类似下面的内容:

    struct any {
  enum type {Int, Float, String};
  any(int   e) { m_data.INT    = e; m_type = Int;}
  any(float e) { m_data.FLOAT  = e; m_type = Float;}
  any(char* e) { m_data.STRING = e; m_type = String;}
  type get_type() const { return m_type; }
  int get_int() const { return m_data.INT; }
  float get_float() const { return m_data.FLOAT; }
  char* get_string() const { return m_data.STRING; }
private:
  type m_type;
  union {
    int   INT;
    float FLOAT;
    char *STRING;
  } m_data;
};
template<typename ...Args>
std::string GetInsertString(const std::string& tableName, Args... args)
{
    std::string insertString = "INSERT INTO ";
    insertString += tableName;
    insertString += " VALUES(";
    std::vector<any> vec = {args...};
    std::ostringstream ss;
    for (unsigned i = 0; i < vec.size(); ++i)
    {
        switch(vec[i].get_type())
        {
            case any::Int:
                ss.str("");
                ss << vec[i].get_int();
                insertString += ss.str() + ",";
                break;
            case any::Float:
                ss.str("");
                ss << vec[i].get_float();
                insertString += ss.str() + ",";
                break;
            case any::String:
                ss.str("");
                insertString += "'" + std::string(vec[i].get_string()) + "'," ;
                break;
        }
    }
    insertString.pop_back();
    insertString += ");";
    return insertString;
}

其中any是基于此链接How can I iterate over a packed variadic template argument list?

的类

但问题是我无法将std::string类型作为variadic参数传递给此函数,因为我们在任何类中都有联合,所以需要你们的帮助来传递{{1键入作为插入查询的值的参数

2 个答案:

答案 0 :(得分:1)

您可以使用虚拟基类,模板包装器和智能指针写一些内容,如下所示

#include <string>
#include <vector>
#include <memory>
#include <sstream>
#include <iostream>


struct anyBase
 { virtual int unusedVirt () { return 0; }; };

template <typename T>
struct anyW : public anyBase
 { 
   T val;

   anyW (T const & v0) : val{v0} { }
 };


struct any
 {
   public: 
      enum type { Int, Float, String };

      any (int e)
         : m_type{Int}, m_data{new anyW<int>(e)} { }

      any (float e)
         : m_type{Float}, m_data{new anyW<float>(e)} { }

      any (char const * e)
         : m_type{String}, m_data{new anyW<std::string>(e)} { }

      any (std::string const & e)
         : m_type{String}, m_data{new anyW<std::string>(e)} { }

      any (any const & a) : m_type{a.m_type}, m_data{nullptr}
       {
         switch ( m_type )
          {
            case Int:
               m_data.reset(new anyW<int>(a.get_int()));
               break;

            case Float:
               m_data.reset(new anyW<float>(a.get_float()));
               break;

            case String:
               m_data.reset(new anyW<std::string>(a.get_string()));
               break;
          }
       }

      type get_type () const { return m_type; }

      int get_int () const
       { return dynamic_cast<anyW<int>*>(m_data.get())->val; }

      float get_float () const
       { return dynamic_cast<anyW<float>*>(m_data.get())->val; }

      std::string const & get_string () const
       { return dynamic_cast<anyW<std::string>*>(m_data.get())->val; }

   private:
      type m_type;

      std::unique_ptr<anyBase> m_data;
 };


template<typename ...Args>
std::string GetInsertString(const std::string& tableName, Args... args)
 {
   std::string insertString = "INSERT INTO ";
   insertString += tableName;
   insertString += " VALUES(";
   std::vector<any> vec = {args...};
   std::ostringstream ss;
   for (unsigned i = 0; i < vec.size(); ++i)
    {
      switch(vec[i].get_type())
       {
         case any::Int:
            ss.str("");
            ss << vec[i].get_int();
            insertString += ss.str() + ",";
            break;
         case any::Float:
            ss.str("");
            ss << vec[i].get_float();
            insertString += ss.str() + ",";
            break;
         case any::String:
            ss.str("");
            insertString += "'" + std::string(vec[i].get_string()) + "'," ;
            break;
       }
    }
   insertString.pop_back();
   insertString += ");";
   return insertString;
 }


int main ()
 {
   std::cout << GetInsertString("fooTable", 1, 2.2f, "3", std::string("4"))
      << std:: endl;
   // print INSERT INTO fooTable VALUES(1,2.2,'3','4');
 }

观察:

  • 此解决方案也适用于C ++ 11

  • 我统一了char *std::string个案;我认为注册chat *

  • 是一个坏主意
  • 使用std::unique_ptr您需要copy_constructor,因为std::unique_ptr中的复制构造函数已被删除,因此删除了任何

  • 的默认复制构造函数
  • 更好的解决方案可能是等待传入(C ++ 17,如果我没错)std::variant

答案 1 :(得分:-2)

typeof

您可以使用typeof并添加切换案例。例如,在新的java中,你可以自动化一个半循环,如果我没有弄错的话,同样可以看到它。