c++ - C++14 中的简单 constexpr LookUpTable

标签 c++ c++14 constexpr lookup-tables

我正在尝试制作一个基于整数数组的简单 LookUpTable,其想法是在编译时计算它.

为了让它能够用于我可能拥有的任何其他 future 的各种整数类型的表,我需要它作为一个模板

所以我有一个LookUpTable.h

#ifndef LOOKUPTABLE_H
#define LOOKUPTABLE_H

#include <stdexcept> // out_of_range

template <typename T, std::size_t NUMBER_OF_ELEMENTS>
class LookUpTableIndexed
{
    private:
        //constexpr static std::size_t NUMBER_OF_ELEMENTS = N;

        // LookUpTable
        T m_lut[ NUMBER_OF_ELEMENTS ] {}; // ESSENTIAL T Default Constructor for COMPILE-TIME INTERPRETER!

    public:
        // Construct and Populate the LookUpTable such that;
        //   INDICES of values are MAPPED to the DATA values stored
        constexpr LookUpTableIndexed() : m_lut {}
        {
            //ctor
        }

        // Returns the number of values stored
        constexpr std::size_t size() const {return NUMBER_OF_ELEMENTS;}

        // Returns the DATA value at the given INDEX
        constexpr T& operator[](std::size_t n)
        {
            if (n < NUMBER_OF_ELEMENTS)
                return m_lut[n];
            else throw std::out_of_range("LookUpTableIndexed[] : OutOfRange!");
        }
        constexpr const T& operator[](std::size_t n) const
        {
            if (n < NUMBER_OF_ELEMENTS)
                return m_lut[n];
            else throw std::out_of_range("LookUpTableIndexed[] const : OutOfRange!");
        }

        using iterator = T*;

        // Returns beginning and end of LookUpTable
        constexpr iterator begin() {return &m_lut[0                 ];}
        constexpr iterator end  () {return &m_lut[NUMBER_OF_ELEMENTS];}
};

#endif // LOOKUPTABLE_H

我正尝试在一个类中使用它来快速衰减一个整数 信号 wrt 一个整数 距离。

例如。这只是 Foo.h

的示例用法
#ifndef FOO_H
#define FOO_H

#include <limits>   // max, digits
#include <stdlib.h> // abs

#include "LookUpTable.h" // LookUpTableIndexed

class Foo
{
private:
    template <typename    TDistance,
              TDistance   MAXIMUM_DISTANCE,
              std::size_t NUMBER_OF_DIGITS>
    struct DistanceAttenuation
    {
    private:
        // Maximum value that can be held in this type
        //constexpr auto MAXIMUM_DISTANCE = std::numeric_limits<TDistance>::max();

        // Number of bits used by this type
        //constexpr auto NUMBER_OF_DIGITS = std::numeric_limits<TDistance>::digits;

        // LookUpTable
        LookUpTableIndexed<TDistance, NUMBER_OF_DIGITS> m_attenuationRangeUpperLimit {}; // ESSENTIAL LookUpTable Default Constructor for COMPILE-TIME INTERPRETER!

        // Returns the number of bits to BIT-SHIFT-RIGHT, attenuate, some signal
        // given its distance from source
        constexpr std::size_t attenuateBy(const TDistance distance)
        {
            for (std::size_t i {NUMBER_OF_DIGITS}; (i > 0); --i)
            {
                // While distance exceeds upper-limit, keep trying values
                if (distance >= m_attenuationRangeUpperLimit[i - 1])
                {
                    // Found RANGE the given distance occupies
                    return (i - 1);
                }
            }
            throw std::logic_error("DistanceAttenuation::attenuateBy(Cannot attenuate signal using given distance!)");
        }

    public:
        // Calculate the distance correction factors for signals
        // so they can be attenuated to emulate the the effects of distance on signal strength
        // ...USING THE INVERSE SQUARE RELATIONSHIP OF DISTANCE TO SIGNAL STRENGTH
        constexpr DistanceAttenuation() : m_attenuationRangeUpperLimit {}
        {
            //ctor

            // Populate the LookUpTable
            for (std::size_t i {0}; (i < NUMBER_OF_DIGITS); ++i)
            {
                TDistance goo = 0; // Not an attenuation calculation
                TDistance hoo = 0; // **FOR TEST ONLY!**
                m_attenuationRangeUpperLimit[i] = MAXIMUM_DISTANCE - goo - hoo;
            }
            static_assert((m_attenuationRangeUpperLimit[0] == MAXIMUM_DISTANCE),
                          "DistanceAttenuation : Failed to Build LUT!");
       }

        // Attenuate the signal, s, by the effect of the distance 
        // by some factor, a, where;
        // Positive contribution values are attenuated DOWN toward ZERO
        // Negative                                    UP          ZERO
        constexpr signed int attenuateSignal(const signed int s, const int a)
        {
            return (s < 0)? -(abs(s) >> a) :
                             (abs(s) >> a);
        }
        constexpr signed int attenuateSignalByDistance(const signed int s, const TDistance d)
        {
            return attenuateSignal(s, attenuateBy(d));
        }

    };

    using SDistance_t = unsigned int;

    constexpr static auto m_distanceAttenuation = DistanceAttenuation<SDistance_t,
                                                                      std::numeric_limits<SDistance_t>::max(),
                                                                      std::numeric_limits<SDistance_t>::digits>();

public:
    Foo() {}
    ~Foo() {}

    // Do some integer foo
    signed int attenuateFoo(signed int signal, SDistance_t distance) {return m_distanceAttenuation::attenuateSignalByDistance(signal, distance);}

};

#endif // FOO_H

我尝试了几种方法,使用 CppCon 2015 的 youtube 视频教程:Scott Schurr “constexpr: Applications” 和其他人,但它不会编译并给出错误;

error: 'constexpr static auto m_distanceAttenuation...' used before its definition

静态断言失败

error: non-constant condition for static assertion

表明它在编译时没有计算任何东西。

我是 C++ 新手。

我知道我在做一些显而易见的事情,但我不知道它是什么。

我是否滥用了 staticconstexpr

numeric_limits 是 constexpr?

我做错了什么? 谢谢。

最佳答案

一些观察

1) as observed by michalsrb , Foo 在初始化 m_distanceAttenuation 时不完整,DistanceAttenuationFoo 的一部分,因此不完整。

不幸的是,您不能初始化类型不完整的 static constexpr 成员(jogojapan in this answer 对此有更好的解释)。

建议:在 Foo 之外(和之前)定义 DistanceAttenuation;所以它是一个完整的类型,可以用来初始化m_distanceAttenuation;像

 template <typename    TDistance,
           TDistance   MAXIMUM_DISTANCE,
           std::size_t NUMBER_OF_DIGITS>
 struct DistanceAttenuation
 {
   // ...
 };

class Foo
{
  // ...
};

2) 在 C++14 中,constexpr 方法不是 const 方法;建议:将以下方法也定义为 const 否则您不能在某些 constexpr 表达式中使用它们

constexpr std::size_t attenuateBy (const TDistance distance) const
constexpr signed int attenuateSignal(const signed int s, const int a) const
constexpr signed int attenuateSignalByDistance(const signed int s, const TDistance d) const

3) 在attenuateBy()中,下面for的测试永远为真

for (std::size_t i {NUMBER_OF_DIGITS - 1}; (i >= 0); --i)

因为 std::size_t 永远是 >= 0,所以 for 进入循环并且永不退出;建议:将i重新定义为intlong

4) 在 attenuateFoo() 中使用 m_DistanceAttenuation,其中变量定义为 m_distanceAttenuation;建议:更正所用变量的名称

5) 在 attenuateFoo() 中,您使用 :: 运算符调用方法 attenuateSignalByDistance();建议:使用 . 运算符,所以(也考虑第 (4) 点)

signed int attenuateFoo(signed int signal, SDistance_t distance)
 {return m_distanceAttenuation.attenuateSignalByDistance(signal, distance);}

关于c++ - C++14 中的简单 constexpr LookUpTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39368547/

相关文章:

C++ 重载加号运算符以将元素添加到对象

c++ - 放置复杂物体

c++ - 将默认赋值运算符声明为 constexpr : which compiler is right?

c++ - 为什么 size_type 在 64 位平台上是 32 位整数?

c++ - g++中的尾递归问题

c++ - 在 C++ 中创建类型列表组合

c++ - `constexpr`和 `const`之间的区别

c++ - 具有非 constexpr 构造函数的 constexpr 非静态成员函数(gcc、clang 不同)

c++ - std::array<int, 10> 作为类成员是零初始化的吗?

c++ - C++11/14/17 中指向方法回调的指针?