C++11:在 std::array<char, N> 上定义函数

标签 c++ c++11

std::array 采用两个模板参数:

typename T // the element type
size_t N // the size of the array

我想定义一个以 std::array 作为参数的函数,但只针对特定的 T,在本例中为 char,但对于任何大小的数组:

以下格式错误:

void f(array<char, size_t N> x) // ???
{
    cout << N;
}

int main()
{
    array<char, 42> A;

    f(A); // should print 42

    array<int, 42> B;

    f(B); // should not compile
}

正确的写法是什么?

最佳答案

使用模板函数:

template<size_t N> void f(array<char, N> x) {
}

关于C++11:在 std::array<char, N> 上定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13547273/

相关文章:

c++ - Horizo​​ntalHeaderView 不调用 QAbstractTableModel 的 child 的 headerData()

c++ - 如何让 LLVM 更喜欢一条机器指令而不是另一条机器指令?

c++ - 包装原子类型并确保它保持原子性

c++ - 使自己的随机数类与 uniform_int_distribution 兼容

c++ - 你怎么能 emplace_back 错误的类型呢?

c++ - 无堆栈 C++20 协程有问题吗?

c++ - 创建新指针循环时,输出取消引用的指针不会增加内存使用量

c++ - 理解 double-to-int 转换中的 int-vs-trunc 关系

c++ - constexpr 未定义行为

c++ - 在带有 std::unique_ptr 的 lambda 中使用 std::bind