使用非size_t整数的std :: array的C ++模板参数推导 [英] C++ template parameter deduction for std::array with non size_t integer

查看:394
本文介绍了使用非size_t整数的std :: array的C ++模板参数推导的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修改避免可变模板函数中的结构到我的需要。但是,我不能理解G ++的行为。考虑以下函数:

I'm trying to adapt the solution presented in Avoiding struct in variadic template function to my need. However, I can't understand the the behavior of G++. Consider the following function:

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

然后调用

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

与GCC抱怨不符

eslong.cpp: In function ‘int main()’:
eslong.cpp:10:38: error: no matching function for call to ‘nextline(std::array<int, 2ul>)’
   nextline(std::array<int, 2> { 1,0 });
                                      ^
eslong.cpp:10:38: note: candidate is:
eslong.cpp:4:5: note: template<class T, unsigned int Size> int nextline(std::array<T, Size>)
 int nextline(const typename std::array<T, Size> ar) {
     ^
eslong.cpp:4:5: note:   template argument deduction/substitution failed:
eslong.cpp:10:38: note:   mismatched types ‘unsigned int’ and ‘#‘integer_cst’ not supported by dump_type#<type error>’
   nextline(std::array<int, 2> { 1,0 });
                                      ^
eslong.cpp:10:38: note:   ‘std::array<int, 2ul>’ is not derived from ‘std::array<T, Size>’

但是,如果我将 unsigned Size 更改为 unsigned long Size size_t 。我不知道这里发生了什么。不是调用 std :: array< T,Size> 参数转换为 size_t

However it matches if I changes unsigned Size to unsigned long Size or size_t. I'm not sure to understand what's happening here. Isn't the Size parameter in the call to std::array<T, Size> converted to a size_t ?

推荐答案

std :: array 模板为:

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

,而大小 N 类型 size_t 。但在你的函数中,你传递一个unsigned(int),不能被解释为 size_t 。根据 SFINAE 如果模板无法扣除,则它不存在,因此您的模板函数不存在。

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.

dyp的其他说明:


[temp.deduct .type] / 17 ,用于需要推导出的事物(模板参数)的类型与其推导的模板参数类型相同的非类型模板参数。

[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.

这篇关于使用非size_t整数的std :: array的C ++模板参数推导的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆