代码之家  ›  专栏  ›  技术社区  ›  PapaDiHatti

获取与int、float等字符串对应的类型

  •  0
  • PapaDiHatti  · 技术社区  · 6 年前

    在c++中,如果我们提供int、float等字符串作为输入,然后它返回相应的类型,有没有办法(函数/结构/模板)等。为了详细说明一个场景,假设我能够从数据库中检索列的数据类型,比如ITEM_NAME具有varchar类型(作为std::string),所以现在我想声明一个c++变量ITEM_NAME(std::string),其类型将与此列ITEM_NAME(varchar)相对应。下面是我尝试过的(示例代码),但这不起作用:

    template<string coltype>
    struct DatabaseType
    {
       typedef COL_TYPE std::string;
    };
    
    template<string coltype="int">
    {
       typedef COL_TYPE int;
    };
    
    std::string getDBType()
    {
    return "int"; 
    }
    int main()
    {
    DataBaseType<std::string("int")>::COL_TYPE x;
    //need to call another overloaded function that returns value corresponding to DB Column name in x
    getDBValue("ITEM_NAME",x); //note this is already defined overloaded function that can take std::string,float and int in place of second argument
    return 0;
    };
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Dmytro Dadyka    6 年前

    template<size_t N>
    struct DatabaseType
    {
       typedef int COL_TYPE;
    };
    
    unsigned constexpr const_hash(char const *input) {
       return *input ?
          static_cast<unsigned int>(*input) + 33 * const_hash(input + 1) :
          5381;
    }
    
    template<>
    struct DatabaseType<const_hash("int")>
    {
       typedef int COL_TYPE;
    };
    
    template<>
    struct DatabaseType<const_hash("float")>
    {
       typedef float COL_TYPE;
    };
    
    template<>
    struct DatabaseType<const_hash("string")>
    {
       typedef std::string COL_TYPE;
    };
    
    void main()
    {
       auto i = DatabaseType<const_hash("int")>::COL_TYPE(10);
       auto f = DatabaseType<const_hash("float")>::COL_TYPE(1.0);
       auto f = DatabaseType<const_hash("string")>::COL_TYPE("dasdas");
    }
    

    enum Types
    {
       TYPE_INT,
       TYPE_FLOAT,
       TYPE_STRING
    };
    
    template<Types N>
    struct DatabaseType
    {
       typedef int COL_TYPE;
    };
    
    template<>
    struct DatabaseType<TYPE_INT>
    {
       typedef int COL_TYPE;
    };
    
    template<>
    struct DatabaseType<TYPE_FLOAT>
    {
       typedef float COL_TYPE;
    };
    
    template<>
    struct DatabaseType<TYPE_STRING>
    {
       typedef std::string COL_TYPE;
    };
    
    
    
    void main()
    {
       auto i = DatabaseType<TYPE_INT>::COL_TYPE(10);
       auto f = DatabaseType<TYPE_FLOAT>::COL_TYPE(1.0f);
       auto f = DatabaseType<TYPE_STRING>::COL_TYPE("dasdas");
    }