简体   繁体   English

模板成员 function 与 stl

[英]Template member function with stl

I have the following existing code snippet in MyQueue.h我在 MyQueue.h 中有以下现有代码片段

class MyQueue {
 struct A {
  explicit A(ValType init){
 }
 ValType memberA;
 };
 struct B {
  explicit B {...}
  std::list<A> listofA; 
 };
 std::unordered_map<std::string, B> myMap;
};

ValType is a know class type defined in a different file. ValType 是在不同文件中定义的已知 class 类型。

GOAL目标

I need to templatize Valtype, meaning struct A constructor (or anywhere Valtype is used) can be Valtype or Valtype2.我需要模板化 Valtype,这意味着 struct A 构造函数(或使用 Valtype 的任何地方)可以是 Valtype 或 Valtype2。

My Questions are as follows我的问题如下

  1. Does the whole class MyQueue need to be a template class or can the relevant member variables and member function be templatized like I have below.整个 class MyQueue 是否需要成为模板 class 或者相关的成员变量和成员 function 可以像我下面那样被模板化。 What are the general rules to decide this?决定这一点的一般规则是什么?

  2. Can stl container be of template type? stl 容器可以是模板类型吗? ex std::unordered_map<std::string, B<T>> myMap; ex std::unordered_map<std::string, B<T>> myMap; std::list<A<T>> listofA;

This class has a cpp file with definitions of class member functions that use A, B and myMap.这个 class 有一个 cpp 文件,其中定义了使用 A、B 和 myMap 的 class 成员函数。

class MyQueue {
 template <class T>
 struct A {
  explicit A(T init){
 }
 T memberA;
 };

 struct B {
  explicit B {...}
  template <class T>
  std::list<A<T>> listofA; 
 };
 template <class T>
 std::unordered_map<std::string, B<T>> myMap;
};

I made the class a template class我将 class 制作为模板 class

template<class TypeName>
class MyQueue {
};

For defining the member functions, I moved definitions from MyQueue.cpp to newly created MyQueue-inl.h which I include at the end of MyQueue.h为了定义成员函数,我将定义从 MyQueue.cpp 移动到新创建的 MyQueue-inl.h 中,我将其包含在 MyQueue.h 的末尾

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

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