如何编写在任意类型的任意容器上运行的模板函数?例如,我如何概括这个虚拟函数
template <typename Element>
void print_size(const std::vector<Element> & a)
{
cout << a.size() << endl;
}
到
template <template<typename> class Container, typename Element>
void print_size(const Container<Element> & a)
{
cout << a.size() << endl;
}
这是一个典型的用法
std::vector<std::string> f;
print_size(f)
这给出错误
tests/t_distances.cpp:110:12: error: no matching function for call to ‘print(std::vector<std::basic_string<char> >&)’. I'm guessing I must tell the compiler something more specific about what types that are allowed.
这个模板使用的变体叫什么,我该如何修复它?
最佳答案
您使用模板模板是否有特定原因?为什么不就这样呢?
template <typename Container>
void print_size(Container const& a)
{
cout << a.size() << endl;
}
一般来说,模板模板不值得麻烦。在你的特定情况下,它们肯定没有用,如果你真的需要访问成员类型,我建议你屈服于常见的做法并使用元函数(typename Container::value_type
in this例)。
关于c++ - 模板模板 C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7555391/