c++ - 模板模板 C++ 函数

标签 c++ templates std

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

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/

相关文章:

c++ - 使用 clang 编译时出现正则表达式段错误,可能是编译器错误?

c++ - 我可以将 Swift 与 C++ 混合使用吗?就像 Objective-C .mm 文件一样

c++ - 在 OpenGL 中绘制扭曲平面的正确方法是什么?

c++ - 如何在 C++ 中将 Foo** 指针转换为 const Foo**

C++:使用指向派生类的指针进行虚函数调用仍然有一个vlookup

c++ - 从类模板中排除类型

css - Rails 应用程序中的主题

c++ - 为多次执行创建makefile

c++ - std::shared_future operator=线程安全/原子?

c++ - 将值转换为 c++ 范围内的值,使用 boost 或 std 进行优化