c++ - 标准容器的类型特征?

标签 c++ templates c++11 typetraits static-assert

<分区>

我查看了 std::type_traits 的列表,但没有看到任何与 std 容器相关的内容。

我希望验证 std 容器是否在编译时传递到模板类型中。

template < typename T >
void foo( T bar )
{
    static_assert( is_std_container??? );
}

最佳答案

它不存在。

如果您知道应该支持的容器类型集,您可以创建自己的特征:

template<class T>
struct is_container
{
    static const bool value = false;
};

template<>
template<class T, class Alloc>
struct is_container<std::vector<T, Alloc>>
{
    static const bool value = true; 
};

// ... same specializations for other containers.

并且您可以像使用其他特征一样使用它:

cout << is_container<std::vector<int>>::value << endl;
cout << is_container<int>::value << endl;

查看here .

请注意,通常您应该将迭代器传递给您的函数,而不是容器。因此,您可以使代码与容器无关并且更加通用。

关于c++ - 标准容器的类型特征?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24284879/

相关文章:

c++ - l-value ref限定成员函数和非限定成员函数之间的区别?

c++ - 如何在 Wt 示例中构建 Widget Gallery?

c++ - 重载 operator<< 和 operator+ 导致错误

c++将类与寺庙结合起来 - 声明其他功能?

c++ - 我不明白在 C++14 的 [namespace.memdef]/3 中的示例中,模板函数如何成为类 A::X::Y 的友元

c++ - 虚拟方法和模板方法 C++

C++ 动态访问成员变量

c++ - 如何使用用户定义的比较结构重置 C++ 映射

c++ - 如何将这个运行时高效的函数变成一个 constexpr?

c++ - 简单的 unique_ptr 问题