Archie Gertsman
Archie Gertsman

Reputation: 1661

C++ Array of Different General Types

Consider this code:

template<typename T>
void doSomething(std::vector<T> arr) {
    for (auto i = 0; i < arr.size(); ++i)
        std::cout << arr[i] << std::endl;
}

int main()
{
    doSomething(std::vector<int> { 1, 5, 7 });
}

In this example, a template is being used quite regularly. An array of three integers is being passed into a function which has a paramater of an array of type T's, general types. It is then specified that they are of type int here: std::vector<int> { 1, 5, 7 }.

What I would like to do is to initialize the std::vector to contain three different types. Something like this:

doSomething(std::vector<T> { 1, "Hi", 2.7f });

Here, there is no specified type, and the std::vector doesn't only contain integers. Is there any way to do such a thing? Thanks!

Upvotes: 1

Views: 1384

Answers (2)

coincoin
coincoin

Reputation: 4685

This is not possible to do that with std::vector. The template argument is unique.

Check std::tuple which can do what you want.

std::tuple<int, std::string, float>

If you need more genericity you will have to do something like this :

template<typename U, typename V, typename W>
void doSomething(std::tuple<U,V,W> t) { ... }

If you want a tuple with an arbitrary number of elements, you must use variadic templates then:

template<typename... Ts>
void doSomething(std::tuple<Ts...> data) {
    // ...
}

Upvotes: 4

Sam Varshavchik
Sam Varshavchik

Reputation: 118435

No, that's not how C++ works. C++ is a statically-typed language. The types of all variables must be declared at compile time.

Other languages, like Perl, Python, Javascript, and others, are dynamically-typed. The type of an object is determined at runtime, so the equivalent array construct in dynamically-typed languages could have values of different types.

Upvotes: 0

Related Questions