本文介绍了是否可以以编程方式初始化constexpr std :: array成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们假设我要编写一个包含成员constexpr std :: array的结构,该结构包含前N个小纤维,其中N是模板参数.

Lets assume I want to write struct that has a member constexpr std::array that contains first N fibs, where N is a template argument.

类似这样的东西,但是在编译时可以使用vals:

Something like this but with vals being avaliable at compile time:

template <int N>
struct first_n_fibs {
    static_assert(N>0);
    static const std::array<int, N> vals;
    static std::array<int, N> init_fibs(){
        std::array<int,N> result;
        if (N==1) {
            return std::array<int,N>{1};
        } else {
            result[0]=1;
            result[1]=1;
            for(int i =2; i<N;++i) {
                result[i]=result[i-2]+result[i-1];
            }
        }
        return result;
    }
};

template<int N>
const std::array<int, N> first_n_fibs<N>::vals=init_fibs();


int main(){
    std::cout << first_n_fibs<2>::vals.back() << std::endl;
    std::cout << first_n_fibs<5>::vals.back() << std::endl;
    std::cout << first_n_fibs<6>::vals.back() << std::endl;
}

我怀疑由于std :: array构造函数不是constexpr,所以没有解决方法,因此,如果有人知道任何涉及C数组或boost的解决方法,我会对此感到满意.

I suspect there is no workaround since std::array constructors are not constexpr, so if somebody knows any workarounds involving C arrays or boost I would be happy with that.

推荐答案

您不需要任何特别的东西,这些天 constexpr 函数的要求非常轻松:

You don't need anything special, constexpr function requirements are very relaxed these days:

#include <iostream>
#include <array>

template <int N> constexpr std::array<int, N> first_n_fibs()
{
    std::array<int, N> ret{};
    ret[0] = 0;
    if (N == 1) return ret;
    ret[1] = 1;
    for (int i = 2; i < N; i++)
        ret[i] = ret[i-2] + ret[i-1];
    return ret;
}

int main()
{
    constexpr auto a = first_n_fibs<3>();
}

(尝试运行)

显然,它没有完全没有用户定义的构造函数,所以没有停止的事情它的构造是 constexpr .

Apparently it has no user-defined constructors at all, so nothing stops its construction from being constexpr.

这篇关于是否可以以编程方式初始化constexpr std :: array成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:47