constexpr在非const成员函数上的用途是什么? [英] What is the use of a constexpr on a non-const member function?

查看:69
本文介绍了constexpr在非const成员函数上的用途是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

字面值constexpr构造函数和函数(不同vc,g ++)的类编译错误显示,在C ++ 14中, constexpr int A :: a() constexpr A :: a()const 可以使用。即成员函数上的 constexpr 并不表示该函数不会更改其作用的对象。

The accepted answer in literal class compile error with constexpr constructor and function (differ vc, g++) shows that in C++14 there is a difference in the way constexpr int A::a() and constexpr A::a() const can be used. i.e. constexpr on a member function does not imply that the function does not change the object it acts on.

给出的示例是:

struct A {
    constexpr A() {}
    constexpr int a() {return 12; }
    constexpr int b() const {return 12; }
};

int main()
{
    constexpr A a;
    // DOES NOT COMPILE as a() is not const
    // constexpr int j = a.a();
    const int k = a.b(); // Fine since b() is const
}

对我来说<$ c $ a()上的c> constexpr 似乎没有用。
constexpr 在非 const 成员函数上是否有具体用途?

To me the constexpr on a() seems useless. Is there a concrete use for constexpr on a non-const member function?

推荐答案

问题:如何创建大小为 1024 的constexpr数组,并将所有元素设置为 0 ,元素元素 42 除外,元素元素必须为 11

Question: how do you create a constexpr array of size 1024 with all elements set to 0 except element element 42 which needs to be 11?

#include <array>

constexpr auto make_my_array() -> std::array<int, 1024>
{
    std::array<int, 1024> a{};
    a[42] = 11; // std::array::operator[] is constexpr non-const method since C++17

    return a;
}

auto test()
{
    constexpr std::array<int, 1024> a = make_my_array();
}

或者来自@ michael-anderson的更好建议a make_iota_array

Or a better yet suggestion from @michael-anderson a make_iota_array:

template <std::size_t N>
constexpr auto make_iota_array() -> std::array<int, N>
{
    std::array<int, N> a{};

    for (std::size_t i = 0; i < N; ++i)
        a[i] = i;

    return a;
}

这篇关于constexpr在非const成员函数上的用途是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆