简体   繁体   中英

C++ Templated STL Container

I'm a C++ novice, and I'm essentially trying to figure out if I can use an STL container as a template which stores whatever type is being passed into it. I don't know if I need to use a class template or define a unique struct or what.

Here's essentially what I have, along with some commentary on what I'd like to achieve:

std::deque<template class T> messages; <--- ???

//the goal being not to store ANY type in this deque, but to somehow
//template it for each type that needs to be stored
//e.g. a different deque for an int, bool, ADT, etc.

template<class T> bool StoreMessage(T const &messageToStore){
     messages<T>.push_back(messageToStore);
}

I have no idea how to even approach this or if this is even possible, but I really don't want to have to write functions for each type that needs to be stored, because there are a lot . Or use void*. I don't want to do that either due to safety and I would still have to explicitly define how to handle each type, even though the process is going to be exactly the same.

Thanks, guys!

Containers are already templated, so what you are trying to do is probably something like this:

template <typename T>
bool store_message(const T &message, std::deque<T> &container) {
    container.push_back(message);
}

To call it, pass both a container by reference and the element:

std::deque<int> numbers;
int el = 5;

store_message(el, numbers);

Actually you can do something like:

#include <deque>

template <class T>
struct container {
   static std::deque<T> messages;
};

template <class T>
std::deque<T> container<T>::messages;

template<class T> bool StoreMessage(T const &messageToStore){
     container<T>::messages.push_back(messageToStore);
}

int main() {
   int a = 10;
   StoreMessage(a);
}

So you want to wrap your variable over additional templated structure and put it into static variable. You need to however declare the static variable to compiler allocate memory to this variable. This is done in lines: template <class T> std::deque<T> container<T>::messages; . To do it properly remember to move everything what is templated to a header file including the memory allocating/declaring stuff... This way you'll be able to access the messages among all your cpp/cc files. All you need to do is to include your created header file in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM