C ++模板 - 指定容器类型及其所包含的容器元素类型 [英] C++ Templates - Specifying a container type and that containers element type that it holds

查看:369
本文介绍了C ++模板 - 指定容器类型及其所包含的容器元素类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要能够创建一个函数,其中我指定一个参数,同时拥有一个模板容器和该容器的模板元素类型。这可能吗?我得到错误C2988:不可扩展的模板声明/定义等。

 模板< class Iter,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;
}
}


解决方案将需要使用模板模板参数,例如

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

但是,请注意,标准库容器需要多个模板参数(向量,例如,需要两个:一个用于存储值类型,一个用于分配器



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

 模板< typename ContainerT> 
void readIntoP(ContainerT aCont)
{
typedef typename ContainerT :: value_type ElementT;
//使用ContainerT和ElementT
}


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) { /* ... */ }

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).

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
}

这篇关于C ++模板 - 指定容器类型及其所包含的容器元素类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆