c++ - 包含特定对象的 STL 容器模板参数

标签 c++ templates stl containers

我有一个函数 f :

template <typename T>
void f(T<int> ints)
{ /* */ }

这个函数应该使用 std::vector<int>std::initializer_list<int>或任何其他 STL 容器,但前提是它包含 int .

我可以忍受接受其他 class es 与 int作为模板参数,但我不希望它接受 std::vector<char>std::vector<double>std::list<double>或类似的东西。

我怎样才能意识到这一点?

最佳答案

可以使用模板模板参数:

template <template <typename...> typename T>
void f(const T<int>& ints)
{ /* */ }

但我建议改用容器的 value_type 类型成员。这将避免将其他模板与 int 作为模板参数进行匹配。

//using std::enable_if_t
template <typename T>
std::enable_if_t<std::is_same<typename T::value_type, int>::value> 
f(const T& ints)
{ /* */ }

//or static_assert
template <typename T>
void f(const T& ints) { 
    static_assert(std::is_same<typename T::value_type, int>::value,
                  "T must be a container of ints"); 
    //...
}

关于c++ - 包含特定对象的 STL 容器模板参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35865707/

相关文章:

python - 将文本与模板进行比较以检测异常(反向模板)

c++ - 从基类型的函数返回派生类对象

c++ - 对 64 位整数中的相邻位进行或运算的有效方法

c++ - 将 CRTP 用于析构函数是否安全?

c++ - 使用相同的接口(interface)传递不同类型的对象

c++ - Sun Studio 12 中的模板编译错误

c++ - 为什么 set/map emplace_hint 不返回 bool 值

c++ - native c++ 指针(例如 uint16 *)上 std::find() 的替代或增强

c++ - 返回 STL 容器元素的引用

c++ - C/C++ 是否有使用相对路径的跨平台方式?