[英]C++ template parameter deduction for std::array with non size_t integer
我正在尝试根据我的需要调整在可变参数模板函数中避免结构中提供的解决方案。 但是,我无法理解 G++ 的行为。 考虑以下函数:
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
参数不是转换为size_t
吗?
std::array
模板化为:
template<class T, std::size_t N > struct array;
而大小N
需要是size_t
类型。 但是在您的函数中,您正在传递一个无法解释为size_t
的 unsigned (int)。 根据SFINAE如果无法推导出模板,则它不存在,因此您的模板化函数不存在。
这不是调用行的问题,而是您对函数模板的声明。 要更正此问题,请使用正确的类型:
template <typename T, size_t Size>
int nextline(const typename std::array<T, Size> ar) {
return 0;
}
在这种情况下,即使您使用:
nextline(std::array<int, 2ul> { 1,0 });
它仍然有效,因为它可以被推断和铸造。
dyp的补充说明:
[temp.deduct.type]/17对于非类型模板参数,需要推导的事物(模板参数)的类型与它被推导的模板参数的类型相同。
您的文字2
被解释为unsigned long
,但您将Size
模板声明为unsigned int
。 只需使用它:
template <typename T, size_t Size>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.