C++模板 - 指定容器类型及其所持有的容器元素类型

发布于 2024-09-13 23:15:55 字数 679 浏览 1 评论 0原文

我希望能够创建一个函数,在其中指定一个参数以同时具有模板化容器和该容器的模板化元素类型。这可能吗?我收到“错误 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;
   }
 }

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

固执像三岁 2024-09-20 23:15:55

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

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

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

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

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

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
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文