C++ 模板 - 指定容器类型和它所拥有的容器元素类型

2022-01-24 00:00:00 containers templates c++ stl

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

I want to be able to create a function where I specify a parameter to have both a templated container and a templated element type for that container. Is this possible? I get "error C2988: unrecongnizable template declaration/definition" among others. Here is the function in question.

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;
   }
 }

推荐答案

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

You would need to use a template template parameter, e.g.,

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

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

Note, however, that the standard library containers take multiple template parameters (vector, for example, takes two: one for the value type to be stored and one for the allocator to use).

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

You might instead use a single template parameter for the instantiated container type and then use its value_type typedef:

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

相关文章