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/