简体   繁体   English

C ++模板化STL容器

[英]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. 我是C ++新手,我实际上是想弄清楚是否可以使用STL容器作为模板来存储要传递给它的任何类型。 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*. 或使用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; 这是通过以下行完成的: 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. 要正确执行此操作,请记住将模板化的所有内容都移动到头文件中,包括内存分配/声明内容...这样,您将能够访问所有cpp / cc文件中的消息。 All you need to do is to include your created header file in it. 您需要做的就是在其中包含创建的头文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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