Col*_*mbo 3 c++ types runtime vector
我有一个程序,需要在程序执行时设置向量的类型(根据配置文件中的值).
我试过这个:
int a = 1
if(a == 1) vector<int> test(6);
else vector<unsigned int> test(6);
test.push_back(3);
Run Code Online (Sandbox Code Playgroud)
但这给了我:
Error 1 error C2065: 'test' : undeclared identifier
Run Code Online (Sandbox Code Playgroud)
我不完全确定原因,但我认为这是因为矢量实际上并不是在编译时决定的,因此编译器在编译其余代码时无法使用它.
有没有办法在运行时决定向量的类型,类似于我上面尝试的?我试图在if之外创建一个版本然后删除它并在IF中重新编写新版本.然而这感觉不对,无论如何我无法让它工作.谢谢.
sep*_*p2k 13
它不起作用的原因是你分别在if-和else-block中声明了向量,因此一旦该块结束它们就会超出范围.
有没有办法在运行时决定向量的类型,类似于我上面尝试的?
不,必须在编译时知道变量的类型.您唯一的选择是将该行test.push_back(3)以及任何访问的代码test放入if-和else-block中,或者避免将代码复制到第二个模板化函数中.这看起来像这样:
template <class T>
do_something_with_test(vector<T>& test) {
test.push_back(3);
// work with test
}
void foo() {
int a = 1
if(a == 1) {
vector<int> test(6);
do_something_with_test(test);
}
else {
vector<unsigned int> test(6);
do_something_with_test(test);
}
}
Run Code Online (Sandbox Code Playgroud)