Struct with two different type properties using templates

422 views c++
4

I want to create a struct which holds a key and a value of different types using templates.

I was thinking about using two template values like this:

template <typename KEY>
template <typename VALUE>
struct KeyValue {
    KEY key;
    VALUE value;
};

int main() {
    KeyValue<int, int> *kv = new KeyValue<int, int>();
}

but this doesn't work. Any suggestions?

answered question

template <typename KEY, typename VALUE> it is obvious.

1 Answer

13

Just put those two arguments in one template

template <typename KEY, typename VALUE>
struct KeyValue {
    KEY key;
    VALUE value;
};

int main() {
    KeyValue<int, int> *kv = new KeyValue<int, int>();
    return 0;
}

And if you want a key-value contaniner, consider std::map

posted this

Have an answer?

JD

Please login first before posting an answer.