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

And*_*zos 3 c++ c++11

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

typename T // the element type
size_t N // the size of the array
Run Code Online (Sandbox Code Playgroud)

我想定义一个函数,它将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
}
Run Code Online (Sandbox Code Playgroud)

写这个的正确方法是什么?

mel*_*ene 6

使用模板功能:

template<size_t N> void f(array<char, N> x) {
}
Run Code Online (Sandbox Code Playgroud)