模板模板C++函数

Nor*_*löw 5 c++ templates std

如何编写在任意类型的任意容器上运行的模板函数?例如,我如何推广这个虚函数

template <typename Element>
void print_size(const std::vector<Element> & a)
{
    cout << a.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)

template <template<typename> class Container, typename Element>
void print_size(const Container<Element> & a)
{
    cout << a.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)

这是一个典型的用法

std::vector<std::string> f;
print_size(f)
Run Code Online (Sandbox Code Playgroud)

这给出了错误

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.
Run Code Online (Sandbox Code Playgroud)

什么是模板使用的这种变体被调用,我该如何解决?

Kon*_*lph 13

您是否有特定原因使用模板模板?为什么不这样呢?

template <typename Container>
void print_size(Container const& a)
{
    cout << a.size() << endl;
}
Run Code Online (Sandbox Code Playgroud)

通常,模板模板不值得麻烦.在你的特定情况下,肯定没有用它们,如果你真的需要访问成员类型,我建议你屈服于常规练习并使用元函数(typename Container::value_type在这种情况下).


zap*_*lom 6

我知道这个问题很久以前就被问过,但我也遇到了同样的问题,解决方案是你需要写

template <template <typename,typename> class Container, typename element, typename Allocator>
void print_size(Container<element, Allocator> & a)
{
    std::cout << a.size() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

因为向量有两个模板参数