Lauen_1

Stay foolish

2-5. Working with Compile Time Constants

#include <array>
#include <cstdint>
#include <iostream>

class MyClass
{
private:
    uint32_t m_Member;

public:
    constexpr MyClass(uint32_t parameter)
        : m_Member{parameter}
    {
    }
    constexpr uint32_t GetValue() const
    {
        return m_Member;
    }
};

int main()
{
    constexpr uint32_t ARRAY_SIZE{ MyClass{ 5 }.GetValue() };
    std::array<uint32_t, ARRAY_SIZE> myArray{ 1, 2, 3, 4, 5 };
    for (auto&& number : myArray)
    {
        std::cout << number << std::endl;
    }
    return 0;
}

 

C++有时候为了运行效率,提供了很多的feature,虽然比较难用

关键字constexpr 就是在编译时进行推导,提升运行效率。

Using constexpr to Define the Size of an array

 1 #include <array>
 2 #include <cstdint>
 3 #include <iostream>
 4 
 5 int main()
 6 {
 7     constexpr uint32_t ARRAY_SIZE{ 5 };
 8     std::array<uint32_t, ARRAY_SIZE> myArray{ 1, 2, 3, 4, 5 };
 9     for (auto&& number : myArray)
10     {
11         std::cout << number << std::endl;
12     }
13     return 0;
14 }

Creating constexpr class Constructors

 

posted on 2016-11-06 16:18  Lauen_1  阅读(174)  评论(0编辑  收藏  举报

导航