C++ std::any 将 std::any 的 C 字符数组转换为字符串的函数

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)除非这是唯一的办法。

编辑:我用它来运行示例https://www.onlinegdb.com/online_c++_compiler

Jar*_*d42 6

的类型"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)

演示

  • 这里,不是 `const X` 与 `X` 的比较,而是指针,所以 `X* const`/`X*` 与 `const X*` 的比较。 (2认同)