簡體   English   中英

c ++聲明一個存儲在字符串中的數據類型的字節數組

[英]c++ declare a byte array of data type which is stored in string

我有一個存儲在 string 中的數據類型名稱。 使用該字符串,我可以聲明該數據類型的變量。

例子,

string s = 'int';

我想創建一個int字節數組。

有沒有辦法在 C++ 中做到這一點?

使用該字符串,我可以聲明該數據類型的變量。

不可以。C++ 是一種靜態類型語言,字符串不是常量表達式。

但是,您可以聲明一個int類型的變量,並根據字符串的內容有條件地使用它:

int foo;
if(str == "int")
    // use foo here

作為旁注: 'int'是一個無效的字符文字; 你可能指的是"int"

最新版本的 boost::variant、std::regex 和 c++14 為我們提供了:

#include <iostream>
#include <string>
#include <boost/variant.hpp>
#include <iomanip>
#include <regex>
#include <stdexcept>
#include <exception>
#include <sstream>

struct variant_value
{
    static auto evaluate(const std::string& s)
    {
        static const std::regex syntax(R"regex((.*)\((.*)\))regex");
        std::smatch result;
        if (std::regex_match(s, result, syntax))
        {

            if (result[1].str() == "int")
            {
                return variant_type(int(std::stoi(result[2].str())));
            }
            if (result[1].str() == "string")
            {
                std::stringstream ss(result[2].str());
                std::string rs;
                ss >> std::quoted(rs, '\'');
                return variant_type(rs);
            }
            if (result[1].str() == "float" || result[1].str() == "double")
            {
                return variant_type(std::stod(result[2].str()));
            }
        }
        throw std::invalid_argument(s);
    }

    variant_value(const std::string& s)
    : _vnt(evaluate(s))
    {}

    template<class F>
    decltype(auto) visit(F&& f) {
        return boost::apply_visitor(std::forward<F>(f), _vnt);
    }

    using variant_type = boost::variant<std::string, int, double>;



    variant_type _vnt;
};

// now test
int main()
{
    auto a = variant_value("string('hello world')");
    auto b = variant_value("int(10)");
    auto c = variant_value("float(6.43)");

    auto print = [](const auto& x) { std::cout << x << std::endl; };

    a.visit(print);
    b.visit(print);
    c.visit(print);

    return 0;
}

預期輸出:

hello world
10
6.43

暫無
暫無

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

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