Huy*_* Le 2 c++ string c-strings rtti stdany
#include <iostream>
#include <any>
#include <string>
#include <vector>
#include <map>
using namespace std;
string AnyPrint(const std::any &value)
{
cout << size_t(&value) << ", " << value.type().name() << " ";
if (auto x = std::any_cast<int>(&value)) {
return "int(" + std::to_string(*x) + ")";
}
if (auto x = std::any_cast<float>(&value)) {
return "float(" + std::to_string(*x) + ")";
}
if (auto x = std::any_cast<double>(&value)) {
return "double(" + std::to_string(*x) + ")";
}
if (auto x = std::any_cast<string>(&value)) {
return "string(\"" + (*x) + "\")";
}
if (auto x = std::any_cast<char*>(&value)) {
return string(*x);
}
}
int main()
{
int a = 1;
float b = 2;
double c = 3;
string d = "4";
char *e = "555";
cout << AnyPrint(a) << "\n";
cout << AnyPrint(b) << "\n";
cout << AnyPrint(c) << "\n";
cout << AnyPrint(d) << "\n";
cout << AnyPrint("555") << "\n";
cout << AnyPrint(e) << "\n";
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试创建一个将std::any对象转换为字符串的函数,因为可能的类型列表是硬编码的。然而,当用户解析原始字符串(如AnyPrint("555"). 我使用Checking std::any's type without RTTI中的方法
当我运行程序时,我得到以下输出:
140722480985696, i int(1)
140722480985696, f float(2.000000)
140722480985696, d double(3.000000)
140722480985696, NSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE string("4")
140722480985696, PKc string("4")
140722480985696, Pc 555
Run Code Online (Sandbox Code Playgroud)
如何处理std::any原始字符串?我不想写,AnyPrint("555"s)除非这是唯一的办法。
的类型"555"可能const char[4]会衰减为const char*。你处理char*,但不是const char*。
处理const char*解决您的问题:
std::string AnyPrint(const std::any &value)
{
std::cout << size_t(&value) << ", " << value.type().name() << " ";
if (auto x = std::any_cast<int>(&value)) {
return "int(" + std::to_string(*x) + ")";
}
if (auto x = std::any_cast<float>(&value)) {
return "float(" + std::to_string(*x) + ")";
}
if (auto x = std::any_cast<double>(&value)) {
return "double(" + std::to_string(*x) + ")";
}
if (auto x = std::any_cast<std::string>(&value)) {
return "string(\"" + (*x) + "\")";
}
if (auto x = std::any_cast<const char*>(&value)) {
return *x;
}
return "other";
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
962 次 |
| 最近记录: |