【问题标题】:C++ Templates - Specifying a container type and that containers element type that it holdsC++ 模板 - 指定容器类型和它所拥有的容器元素类型
【发布时间】:2010-08-10 23:58:08
【问题描述】:

我希望能够创建一个函数,在其中我指定一个参数以同时具有模板化容器和该容器的模板化元素类型。这可能吗?我收到“错误 C2988:无法识别的模板声明/定义”等。这是有问题的函数。

template<class Iter, class Elem>
 void readIntoP(Iter<Elem> aCont){
ifstream ifss("data.dat");
string aString;
int counter = 0;
item tempItem;
while(ifss >> aString){
    istringstream iss(aString);
    if(counter == 0){
        tempItem.name = aString;
    }else if(counter == 1){
        int aNum = 0;
        iss >> aNum;
        tempItem.iid = aNum;
    }else{
        double aNum = 0;
        iss >> aNum;
        tempItem.value = aNum;
        aCont.push_back(tempItem);
        counter = -1;
    }
    ++counter;
   }
 }

【问题讨论】:

标签: c++ templates stl containers


【解决方案1】:

您需要使用模板模板参数,例如,

template <template <class> class Iter, class Elem>
void readIntoP(Iter<Elem> aCont) { /* ... */ }

但请注意,标准库容器采用多个模板参数(例如,vector 采用两个:一个用于存储值类型,一个用于分配器使用)。

您可以改为对实例化的容器类型使用单个模板参数,然后使用其value_type typedef:

template <typename ContainerT>
void readIntoP(ContainerT aCont)
{
    typedef typename ContainerT::value_type ElementT;
    // use ContainerT and ElementT
}

【讨论】:

  • 在迭代器上参数化通常比在容器上参数化更好。 (这就是 OP 正在做的事情。)
  • @Potatoswatter:很难说。问题标题和变量名暗示 OP 正在尝试传递一个容器;类型名意味着 OP 正在尝试传递某种迭代器。不管怎样,迭代器也有一个value_type typedef。我同意一般来说传递迭代器而不是容器更好,但传递整个容器通常很有用。
  • 我听说标准没有规定一个容器有多少个参数。一个向量至少有两个,但实现可能会出于自己的目的添加更多,从而使“模板模板”的可移植性降低?
  • @UncleBens:Johannes Schaub 询问了a question about that,答案是标准确实指定了容器的参数必须是什么
  • @James McNellis -> 您能否描述对模板参数“template class Iter”如何工作的理解(我在遵循逻辑时遇到了麻烦)。另外,我很感兴趣,为什么在迭代器上参数化比在容器上更好?顺便说一句,感谢您所有非常快速的答案! :d @James McNellis & Potatoswatter -> 很抱歉我的模板被称为“iter”,因此产生了误解。我一开始打算走迭代器路线,后来决定试试这个容器路线,但忘了适当地改变它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-10
  • 1970-01-01
  • 2010-12-15
相关资源
最近更新 更多