今天写c++ 遇到一个场景,需要往一个变量里放入不同类型的值
引入头文件:
#include <variant>
using AttributeValue =
std::variant<bool,
int32_t,
int64_t,
uint32_t,
double,
// const char *,
std::string,
std::string_view,
const char*,
std::vector<bool>,
std::vector<int32_t>,
std::vector<int64_t>,
std::vector<uint32_t>,
std::vector<double>,
std::vector<std::string_view>,
// Not currently supported by the specification, but reserved for future use.
// Added to provide support for all primitive C++ types.
uint64_t,
// Not currently supported by the specification, but reserved for future use.
// Added to provide support for all primitive C++ types.
std::vector<uint64_t>,
// Not currently supported by the specification, but reserved for future use.
// See https://github.com/open-telemetry/opentelemetry-specification/issues/780
std::vector<uint8_t>>;
辨别类型
void OtlpRecordable::PopulateAttribute(KeyValue *attribute,
const std::string& key,
const AttributeValue &value) const {
if (key.empty()) {
return;
}
attribute->set_key(key);
if (std::holds_alternative<bool>(value))
{
attribute->mutable_value()->set_bool_value(std::get<bool>(value));
return;
}
else if (std::holds_alternative<int>(value))
{
attribute->mutable_value()->set_int_value(std::get<int>(value));
return;
}
else if (std::holds_alternative<int64_t>(value))
{
attribute->mutable_value()->set_int_value(std::get<int64_t>(value));
return;
}
else if (std::holds_alternative<unsigned int>(value))
{
attribute->mutable_value()->set_int_value(std::get<unsigned int>(value));
return;
}
else if (std::holds_alternative<uint64_t>(value))
{
attribute->mutable_value()->set_int_value(std::get<uint64_t>(value));
return;
}
else if (std::holds_alternative<double>(value))
{
attribute->mutable_value()->set_double_value(std::get<double>(value));
return;
}
else if (std::holds_alternative<const char *>(value))
{
attribute->mutable_value()->set_string_value(std::get<const char *>(value));
return;
}
else if (std::holds_alternative<std::string_view>(value))
{
attribute->mutable_value()->set_string_value(std::get<std::string_view>(value).data(),
std::get<std::string_view>(value).size());
return;
}
else if (std::holds_alternative<std::string>(value))
{
attribute->mutable_value()->set_string_value(std::get<std::string>(value));
return;
}
}