Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2021-02-14 12:50:14

0001 #ifndef _CommonTools_Utils_StringToEnumValue_h_
0002 #define _CommonTools_Utils_StringToEnumValue_h_
0003 
0004 #include "FWCore/Utilities/interface/Exception.h"
0005 #include "TEnum.h"
0006 #include "TEnumConstant.h"
0007 #include <cassert>
0008 #include <string>
0009 #include <sstream>
0010 #include <vector>
0011 
0012 /**
0013 
0014    Convert a string into the enum value it corresponds to. Example:
0015    <code>
0016    int value = StringToEnumValue<EcalRecHit::Flags>("kGood");
0017    </code>
0018 
0019    \author Stefano Argiro
0020    \version $Id: StringToEnumValue.h,v 1.5 2012/08/28 22:28:38 wmtan Exp $
0021    \date 04 Mar 2011
0022 */
0023 
0024 template <typename MyEnum>
0025 int StringToEnumValue(std::string const& enumConstName) {
0026   TEnum* en = TEnum::GetEnum(typeid(MyEnum));
0027   if (en != nullptr) {
0028     if (TEnumConstant const* enc = en->GetConstant(enumConstName.c_str())) {
0029       return enc->GetValue();
0030     }
0031   }
0032   assert(0);
0033   return -1;
0034 }
0035 
0036 /**
0037 
0038    Convert a vector<string> into a vector<int> with the enum values 
0039    it corresponds to. Example:
0040 
0041    <code>
0042    std::vector<std::string> names;
0043    names.push_back("kWeird");
0044    names.push_back("kGood");
0045    
0046    std::vector<int> ints =  StringToEnumValue<EcalRecHit::Flags>(names);
0047    
0048 
0049    std::copy(ints.begin(), ints.end(), 
0050              std::ostream_iterator<int>(std::cout, "-"));
0051    </code>
0052 
0053 
0054 */
0055 
0056 template <class MyType>
0057 std::vector<int> StringToEnumValue(const std::vector<std::string>& enumNames) {
0058   using std::string;
0059   using std::vector;
0060 
0061   vector<int> ret;
0062   vector<string>::const_iterator str = enumNames.begin();
0063   for (; str != enumNames.end(); ++str) {
0064     ret.push_back(StringToEnumValue<MyType>(*str));
0065   }
0066   return ret;
0067 
0068 }  //
0069 
0070 #endif