采用 std::vector 或 std::array 的模板函数

2024-05-11

我有一个函数,当前接受 2 个向量,其中可以包含任何普通的旧数据......

template <class T>
void addData(const vector<T>& yData, vector<T> xData)
{ .. }

问题:

  • 是否可以修改为需要两个std::array or two std::vector,或者甚至是它们的组合,考虑到这些容器采用不同数量的模板参数?

当然,这只是创建一个合适的类型特征的问题。该示例仅使用一个函数f()只有一个参数,但扩展以接受任意数量的参数是微不足道的。

#include <array>
#include <vector>
#include <deque>
#include <utility>
#include <cstddef>

template <typename T>
struct is_array_or_vector {
    enum { value = false };
};

template <typename T, typename A>
struct is_array_or_vector<std::vector<T, A>> {
    enum { value = true };
};

template <typename T, std::size_t N>
struct is_array_or_vector<std::array<T, N>> {
    enum { value = true };
};

template <typename T>
typename std::enable_if<is_array_or_vector<T>::value>::type
f(T const&)
{
}

int main()
{
    f(std::vector<int>());    // OK
    f(std::array<int, 17>()); // OK
    f(std::deque<int>());     // ERROR
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

采用 std::vector 或 std::array 的模板函数 的相关文章

随机推荐