文字列に格納されているデータ型名があります。 その文字列で、そのデータ型の変数を宣言できますか?C++は、文字列に格納されているデータ型のバイト配列を宣言します。
例、
string s = 'int';
私はint
のバイト配列を作成したいです。
C++で行う方法はありますか?
文字列に格納されているデータ型名があります。 その文字列で、そのデータ型の変数を宣言できますか?C++は、文字列に格納されているデータ型のバイト配列を宣言します。
例、
string s = 'int';
私はint
のバイト配列を作成したいです。
C++で行う方法はありますか?
この文字列を使用すると、そのデータ型の変数を宣言できますか?
いいえ。C++は静的型付き言語であり、文字列は定数式ではありません。
ただし、タイプint
の変数を宣言し、条件付き文字列の内容に応じて、それを使用することができます。
int foo;
if(str == "int")
// use foo here
追記として:'int'
リテラル無効な文字です。あなたはおそらく"int"
を意味するでしょう。
あなたはもう一歩進んで、ここで組合を使うことができます。 – OMGtechy
@OMGtechy確かに、私たちは別のステップを踏んで、すでに言及した変種を使用することができます。 – user2079303
ブーストの最新バージョン::バリアント、のstd ::正規表現と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
番号とは言うものの、あなたが望むかもしれませんバリアントを見る – OMGtechy
提案をいただきありがとうございます。私はそれを試してみます – Saravana