C++ 非size_t整数的 std::数组的模板参数推导
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
类型。但是在你的函数中,你传递了一个无符号的(int),它不能被解释为size_t
。根据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>
相关文章:
- C++函数模板需要 &for 数组参数
- C++ 数组参数不起作用
- 使用数组参数进行函数专用化
- 为什么我的数组参数的方法无法正常工作?(C )
- SWIG - Java 代理类数组参数
- 在 gcc 中使用数组参数编译外部"c"代码
- 从 VB6 调用的 C++ DLL 函数中的输出数组参数
- 如何根据数组参数项类型重载 IDL 中的函数
- 引用谷歌测试/模拟框架中的数组参数
- C++将数组参数传递给函数
- 字符星形数组参数未正确终止
- 如何将德尔菲的"字符串数组"参数翻译成C++?
- 为什么 gcc 无法推断数组参数的模板化大小?(C++11)
- 使用 const char 数组参数分析 constexpr 显示运行时执行
- C++指针数组参数
- 固定大小的多维数组参数
- 为什么数组参数被视为常量数组
- 如何在pgsql中格式化数组参数
- C++字符数组参数在x86编译中包含奇怪的字符
- 对象数组参数 - 错误:字段“字母”的类型不完整