簡體   English   中英

C++ std::any function 將 std::any C 字符數組轉換為字符串

[英]C++ std::any function that convert std::any of C char-array to string

#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;
}

我正在嘗試制作一個 function 將std::any object 轉換為字符串,因為可能的類型列表是硬編碼的。 但是,當用戶解析AnyPrint("555")之類的原始字符串時會出現問題。 我使用Checking std::any's type without RTTI中的方法

當我運行程序時,我得到以下 output:

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

如何處理std::any原始字符串? 我不想寫AnyPrint("555"s)除非這是唯一的方法。

編輯:我用它來運行示例https://www.onlinegdb.com/online_c++_compiler

"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";
}

演示

如評論中所述,像"555"這樣的字符串文字是(或衰減為) const char*指針。 您的AnyPrint function 不處理此類參數類型。

添加以下塊可解決問題:

    if (auto x = std::any_cast<const char*>(&value)) {
        return string(*x);
    }

另外,請注意行, char *e = "555"; 在 C++ 中是非法的; 你需要const char *e = "555"; 或者char e[] = "555"; ; 使用后者將展示std::any_cast<T>塊中的char* (使用AnyPrint(e) )和const char* (使用AnyPrint("555") )類型之間的區別。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM