dimanche 2 septembre 2018

C++ Template function with is_same type_trait not working for type T=std::string

I have implemented a simple Xerces-c based C++ library for parsing and reading data items from XML config files. I provide facility to convert data types read into int, long, double, bool, float and string.

All items work fine except std::string where any conversion is not needed. I would simply like to compare using traits and return but it does not work. is_same works only for built in types ?

template<typename T> T CppXMLConfigReader::getTypeVal(const std::string& key, const T& defaultVal) const
{
    T returnVal = defaultVal;
    auto iter = m_configMapItems.find(key.c_str());
    if(iter != m_configMapItems.end())
    {
        try
        {
            if(is_same<T,int>::value)
                returnVal = stoi(iter->second);
            if(is_same<T,float>::value)
                returnVal = stof(iter->second);
            if(is_same<T,long>::value)
                returnVal = stol(iter->second);
            if(is_same<T,double>::value)
                returnVal = stod(iter->second);
            if(is_same<T,bool>::value)
            {
                if(iter->second == "true" || iter->second == "1")
                    returnVal=true;
                else
                    returnVal=false;
            }
            if(is_same<T,string>::value)   // Error is from here.
                returnVal = iter->second;  // Error is from here.
        }
        catch(const invalid_argument& e)
        {
            cout << "Exception happened while converting " << iter->second << " Into rqequired type. Please investigate." << endl;
        }
    }
    return(returnVal);
}

Aucun commentaire:

Enregistrer un commentaire