简体   繁体   English

使用字符串指定向量的类型

[英]Specify the type of a vector with a string

How do you specify a type with a string? 如何指定带字符串的类型? I mean: 我的意思是:

string s = "int";
Vector<s> vec;

And I want vec to be vector<int> . 我希望vec是vector<int> Is this possible? 这可能吗?

I want to make a class where the user can type in a string and a vector with that type will be created. 我想创建一个用户可以键入字符串的类,并创建具有该类型的向量。

Not possible in C++, atleast not the way you want. 在C ++中不可能,至少不是你想要的方式。

Templates are a compile time concept, while user input is a runtime concept. 模板是编译时的概念,而用户输入是运行时概念。 Completely different, not mixable. 完全不同,不可混合。

To make that work, you need a dynamically typed language, which C++ is not. 要做到这一点,你需要一种动态类型的语言,而C ++则不然。 It's statically typed. 它是静态类型的。

Is this possible? 这可能吗?

This is not possible in C++. 这在C ++中是不可能的。 If using boost is an option, consider creating a vector of boost::variant objects instead: this way, your statically-typed vector would be prepared to accept elements of different types. 如果使用boost是一个选项,请考虑创建一个boost::variant对象的向量:这样,您的静态类型vector将准备接受不同类型的元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM