c++:为什么不能使用模板来推断容器和元素类型?

标签 c++ class templates containers typename

我有一个非常简单的测试程序,如下所示:

#include<vector>
#include<iostream>
using namespace std;
template<typename C, typename E>
void f(const C<E>& container){
    cout<<container.size()<<endl;
}
int main(){
    vector<int> i;
    f(i);
    return 0;
}

它无法用 gcc 4.1.2 编译。错误信息是:

templateContainer.cpp:5: error: ‘C’ is not a template
templateContainer.cpp: In function ‘int main()’:
templateContainer.cpp:10: error: no matching function for call to ‘f(std::vector<int, std::allocator<int> >&)’

最佳答案

您可以使用模板模板参数(请注意,std::vector 实际上采用多个模板参数[一种元素类型和一种分配器类型]) .:

template<template <typename...> class C, typename... E>
void f(const C<E...>& container){
    cout<<container.size()<<endl;
}

Live Demo


如果不需要类型分解,可以简单地使用普通模板。

template<typename C>
void f(const C& container){
    cout<<container.size()<<endl;
}

您还可以从 STL 容器中获取 typedef:例如,如果您想知道容器中元素的类型value_type 就在那里。

template<typename C>
void f(const C& container){
    using ValueType = typename C::value_type;
    cout<<container.size()<<endl;
}

关于c++:为什么不能使用模板来推断容器和元素类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44655222/

相关文章:

class - Lua 检查表是否为 'instance'

C++ 重写虚拟模板方法

c++ - 模板类型名

templates - 如何使用结构或变量值的字段作为模板名称?

C++::使用 vector 迭代器调用类方法?

c++ - 非类型模板参数错误 ('x' is not a type)

c++ - 使用 boost::spirit::qi 解析 double 列表

c++ - 从表创建统计数据

c++ - 我该如何解决错误 C2059 : syntax error : 'string' "

c# - 如何在 C# 中创建类列表