Set vector type at runtime

I have a program that should set the type of the vector when the program is running (according to the value in the configuration file).

I tried this:

int a = 1

if(a == 1)  vector<int> test(6);
else  vector<unsigned int> test(6);

test.push_back(3);

But it gives me:

Error   1   error C2065: 'test' : undeclared identifier

I'm not quite sure why, but I think this is due to the fact that at the time of compilation the vector was not actually solved, so the compiler cannot work with it, compiling the rest of the code.

Is there a way to determine the type of a vector at runtime, similar to what I tried to do above? I tried to create one version outside if, and then delete it and overwrite the new version inside IF. This, however, is not the case, and I cannot get it to work. thanks.

+3
source share
7

, , , if- else- , .

, , ?

, . - 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);
    }
}
+13

, , , test. , if, , , , .

, . , .

if(a == 1)
{
  vector<int> test(6);
}
else
{
  vector<unsigned int> test(6);
}

test.push_back(3);

, , , , , . , , , , , , , .

+4

, , , -

union DataType
{
    int intVal;
    unsigned uintVal;
}
std::vector<DataType> vec;

, , boost:: variant . , , .

!

+3
+2

(, ) . .

+1

, , boost:: variant - .
++ ( ). "vector <Variant> a" a.push_back (Variant ((unsigned int)..). , , .

, , , .

, , , (, , ++ ).

( ) . ++ 0x "auto" decltype().

, , , , float.

(, makefile), , . , , , .

0

test, if, . , test.push_back(3);, test, .

, : , int unsigned int , vector<int>, , t int.

-1

Source: https://habr.com/ru/post/1717718/


All Articles