存在的原因是std::decay什么?在什么情况下std::decay有用?
显然,我们可以将复杂的类实例传递给函数,但为什么我们不能将数组传递给函数呢?
我有以下代码:
template <typename T, typename sepT = char>
void print2d(const T &data, sepT sep = ',') {
for(auto i = std::begin(data); i < std::end(data); ++i) {
decltype(*i) tmp = *i;
for(auto j = std::begin(tmp); j < std::end(tmp); ++j) {
std::cout << *j << sep;
}
std::cout << std::endl;
}
}
int main(){
std::vector<std::vector<int> > v = {{11}, {2,3}, {33,44,55}};
print2d(v);
int arr[2][2] = {{1,2},{3,4}};
print2d(arr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我更改decltype为auto,它将无法编译和抱怨(部分错误):
2d_iterator.cpp: In instantiation of ‘void print2d(const T&, …Run Code Online (Sandbox Code Playgroud)