C++ c++;声明以字符串形式存储的数据类型的字节数组
我有一个存储在字符串中的数据类型名称。 使用该字符串,我可以声明该数据类型的变量 例如C++ c++;声明以字符串形式存储的数据类型的字节数组,c++,C++,我有一个存储在字符串中的数据类型名称。 使用该字符串,我可以声明该数据类型的变量 例如 string s = 'int'; 我想创建int的字节数组 在C++中有什么方法?< /P> 使用该字符串,我可以声明该数据类型的变量 > C++是静态类型的语言,字符串不是常量表达式。 但是,您可以声明类型为int的变量,并根据字符串的内容有条件地使用它: int foo; if(str == "int") // use foo here 作为旁注:'int'是无效的字符文本;您可能是指“i
string s = 'int';
我想创建int
的字节数组
<>在C++中有什么方法?< /P>
使用该字符串,我可以声明该数据类型的变量
<> > 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;
}
不。尽管如此,您可能想看看变体。谢谢您的建议。我会尝试让您可以更进一步,在这里使用联合体。@OMGtechy当然可以,我们可以采取另一步,使用您已经提到的变体。
hello world
10
6.43