c – constexpr函数向数组添加整数
我正在尝试实现一个constexpr函数“add42”,这将允许我这样做:
constexpr array<int,5> arr = {1,2,3,4,5}; constexpr array<int,5> arr2 = add42(0,arr); //I want arr2=={43,5} 也就是说,将给定索引处的整数静态地添加到数组(使用constexpr). template<int DIM,typename... ARGS> auto constexpr add42(int index,array<int,DIM> intergerArray,ARGS... unpackedIntegers) -> array<int,DIM> { return ( sizeof...(ARGS)==DIM ) ? array<int,DIM>( {{unpackedIntegers...}} ) : ( (sizeof...(ARGS)-1)==index ) ? add42(index,intergerArray,unpackedIntegers...,intergerArray[sizeof...(ARGS)-1]+42 ) : add42(index,intergerArray[sizeof...(ARGS)-1] ) ; } 也就是说,我的数组的所有整数都是从数组中递归解压缩的,如果在正确的索引处添加42,并且在ARGS列表的末尾附加.当这个arg列表包含数组中的所有整数时,我们就完成了,所以我们可以重新打包成一个新数组. 但是我得到了这个错误(gcc 4.7.2) error: no matching function for call to 'add42(int,const std::array<int,5u>&)'| note: candidate is:| template<int DIM,class ... ARGS> constexpr std::array<int,DIM> add42(int,std::array<int,DIM>,ARGS ...)| note: template argument deduction/substitution failed:| note: mismatched types 'int' and '#'integer_cst' not supported by dump_type#<type error>'| 你能解释一下我的问题是什么以及如何纠正它? 这个问题看起来与C++11: Compile Time Calculation of Array类似但不是(至少,我无法弄清楚如何直接使用它):在这里,我想从已经存在的数组创建一个新数组,而不是从已知的整数序列创建. 编辑 现在我得到了无限的实例化,即使没有调用递归也是如此.这是一个简化的例子: template<size_t DIM,DIM> integerArray,DIM> { return ( true ) ? array<int,DIM>( {{unpackedIntegers...}} ) : add42(index,integerArray,integerArray[(sizeof...(ARGS)-1)] ) ; } 为什么我的编译器会尝试编译最后一个函数调用? 编辑2 显然,我必须提供2个函数,以免混淆编译器: template<size_t DIM,class... ARGS> constexpr auto add42(int index,ARGS... unpackedIntegers) -> typename enable_if<sizeof...(ARGS)==DIM,DIM>>::type { return array<int,DIM>( {{unpackedIntegers...}} ); } template<size_t DIM,ARGS... unpackedIntegers) -> typename enable_if<sizeof...(ARGS)!=DIM,DIM>>::type { return ( sizeof...(ARGS) == index ) ? add42(index,integerArray[sizeof...(ARGS)]+42) : add42(index,integerArray[sizeof...(ARGS)]) ; } 但它仍然不起作用: recursively required from [[name of the second function]] 显然,可变参数函数不能“递归地”调用其重载之一. 解决方法
你应该用
template<size_t DIM,ARGS... unpackedIntegers) 因为数组的第二个参数的类型是size_t,而不是int. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |