Last active
November 15, 2018 18:34
-
-
Save kgbook/beb70edd2014256477e3b78bc4c79b05 to your computer and use it in GitHub Desktop.
[boost variant example]boost::variant example #boost #variant
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <boost/variant.hpp> | |
#include <string> | |
#include <iostream> | |
using data_t = boost::variant< | |
bool, | |
int8_t, | |
uint8_t, | |
int16_t, | |
uint16_t, | |
int32_t, | |
uint32_t, | |
int64_t, | |
uint64_t, | |
float, | |
double, | |
std::string>; | |
enum class DataType { /* use type_t */ | |
kBool, | |
kInt8, | |
kUint8, | |
kInt16, | |
kUint16, | |
kInt32, | |
kUint32, | |
kInt64, | |
kUint64, | |
kFloat, | |
kDouble, | |
kString, | |
kSize /* not type, denote the size */ | |
}; | |
using type_t = DataType; | |
template <class T> | |
bool getBaseData(type_t type, data_t param, T& t) { | |
switch (type) { | |
case type_t::kBool: { | |
t = boost::get<bool>(param); | |
break; | |
} | |
case type_t::kInt8: { | |
t = boost::get<int8_t>(param); | |
break; | |
} | |
case type_t::kUint8: { | |
t = boost::get<uint8_t>(param); | |
break; | |
} | |
case type_t::kInt16: { | |
t = boost::get<int16_t>(param); | |
break; | |
} | |
case type_t::kUint16: { | |
t = boost::get<uint16_t>(param); | |
break; | |
} | |
case type_t::kInt32: { | |
t = boost::get<int32_t>(param); | |
break; | |
} | |
case type_t::kUint32: { | |
t = boost::get<uint32_t>(param); | |
break; | |
} | |
case type_t::kInt64: { | |
t = boost::get<int64_t>(param); | |
break; | |
} | |
case type_t::kUint64: { | |
t = boost::get<uint64_t>(param); | |
break; | |
} | |
case type_t::kString: { | |
// t = boost::get<std::string>(param); | |
break; | |
} | |
default: { | |
return false; | |
} | |
} | |
return true; | |
} | |
void getStringData(type_t type, data_t param, std::string &str) { | |
str = boost::get<std::string>(param); | |
} | |
int main() | |
{ | |
data_t stringData = "hello"; | |
data_t doubleData = 3.1415926; | |
double dData; | |
std::string strData; | |
getBaseData(type_t::kDouble, doubleData, dData); | |
getStringData(type_t::kString, stringData, strData); | |
std::cout <<"dData:" <<dData <<", strData:" <<strData <<std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment