有什么方法可以让它自动检测 std::array 中的大小<int,5>

问题描述 投票:0回答:1
template<typename T, size_t N>
void print(const std::array<T,N>& data){ 
  for(auto it : data){
    std::cout << it << std::endl;
  }
}

int main(){
 
  std::array<int,5> arr{1,2,3,4,5};

  print(arr);    ^
                 |

  /* Here in main method in the std::arr<int,5>
     I am explicitly specifying the size of the
     array but I'll need just like template
     it should detect size automatically
     and I don't want to specify the size
     explicitly */
}

我尝试过:

template <typename Container>
void print(const Container& container)
{   
  std::copy(std::begin(container),
     std::end(container), std::ostream_iterator<typename Container::value_type> (std::cout," "))
}

而且效果很好,就像这样。我需要模板而不需要像这样在

std::array<int,5>
中明确指定大小。

c++ stl c++17
1个回答
0
投票

C++17 引入了类模板参数推导。因此,只需完全删除模板参数即可:

std::array arr{1,2,3,4,5};
© www.soinside.com 2019 - 2024. All rights reserved.