【发布时间】:2017-05-30 06:28:42
【问题描述】:
在 C++ 中有什么方法可以通过我可以将程序中的数据类型(如(int、char、std::string 等)存储在某种特定类型的变量中,然后使用该变量代替常规数据类型(例如:声明其他变量)?
例如:-
T = some-function("int")
now std::vector < T > is equivalent to std::vector <int> ?
【问题讨论】:
-
在运行时执行此操作需要reflection,而 C++ 没有。一旦源文件被编译成translation unit,大多数类型信息就消失了。为了在编译时使用 templates,任何good beginners book 都应该有帮助。
-
使用模板。如果您想要在编译时不知道的泛型类型,请使用
std::variant