C++ template parameter deduction for std::array with non size_t integer

心已入冬 提交于 2019-12-01 17:55:40
texasbruce

std::array is templated as:

template<class T, std::size_t N > struct array;

while the size N is required to be the type size_t. But in your function, you are passing an unsigned (int) which cannot be interpreted as size_t. According to SFINAE If a template cannot be deducted, it does not exist, thus your templated function does not exist.

It is NOT the problem with the call line, but your declaration of your function template. To correct this, use the correct type:

template <typename T, size_t Size>
int nextline(const typename std::array<T, Size> ar) {
  return 0;
 }

In this case, even you use:

nextline(std::array<int, 2ul> { 1,0 });

It still works because it can be deducted and casted.


Additional explanation by dyp:

[temp.deduct.type]/17 for non-type template parameters that requires the type of the deduced thing (template-argument) to be of the same type as the template-parameter it is deduced for.

Your literal 2 is interpreted as an unsigned long, but you are declaring the Size template to be an unsigned int. Just use this instead:

template <typename T, size_t Size>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!