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

3

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
}

如何正确地书写这个?

2个回答

6

使用模板函数:

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

这个 f(A) 函数会正确推断出 N 吗?还是需要指定为 f<42>(A) - Andrew Tomazos
@AndrewTomazos-Fathomling 是的,它会推断出来。 - jogojapan

2

N需要是一个静态值。例如,您可以将其作为模板参数:

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

在你的例子中,我仍然会通过引用传递参数:
template <std::size_t N>
void f(std::array<char, N> const& x) {
    ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接