加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – constexpr函数向数组添加整数

发布时间:2020-12-16 09:45:08 所属栏目:百科 来源:网络整理
导读:我正在尝试实现一个constexpr函数“add42”,这将允许我这样做: constexpr arrayint,5 arr = {1,2,3,4,5};constexpr arrayint,5 arr2 = add42(0,arr); //I want arr2=={43,5} 也就是说,将给定索引处的整数静态地添加到数组(使用constexpr). 由于我的数组“ar
我正在尝试实现一个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).
由于我的数组“arr”是不可变的,我实际上必须从“arr”和我的索引创建一个新的.这就是我编写这个函数的原因:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读