Pirogov
Pirogov

Reputation: 37

C++ templates and container of templates. How to iterate template vector with template objects

Consider we have template structure keyVal.

template<typename T>
struct keyVal
{
    std::string key;
    T val;
};

I want store them in vector. So i have template vector:

template<typename T>
std::vector<T> vec;

I can store my struct like this:

keyVal<int> v{"key", 1};
keyVal<int> v1{"key1", 2};

vec<keyVal<int>>.push_back(v);
vec<keyVal<int>>.push_back(v1);

But i've met a problem. If i create new instance of keyVal struct like this:

keyVal<std::string> v2{"key2", "w"};

I can store it to the template vec fine:

vec<keyVal<std::string>>.push_back(v2);

How can i iterate over this vector and get all structures if i don't know what type there are?

Full code:

#include <iostream>
#include <vector>
#include <map>

template<typename T>
std::vector<T> vec;

template<typename T>
struct keyVal
{
    std::string key;
    T val;
};

int main()
{

    keyVal<int> v{"key", 1};
    keyVal<int> v1{"key1", 2};
    keyVal<std::string> v2{"key2", "w"};

    vec<keyVal<int>>.push_back(v);
    vec<keyVal<int>>.push_back(v1);
    vec<keyVal<std::string>>.push_back(v2);

    //auto t = vec<T>.at(0); ???

    return 0;
}

Upvotes: 0

Views: 45

Answers (1)

Joseph Larson
Joseph Larson

Reputation: 9058

If I were going to store a vector of these guys, and they were going to hold random types, then I would have your original template inherit from a class that an abstract base class, and I'd have the abstract base class define the entire interface, as much as I could.

Upvotes: 1

Related Questions