如何模板化移位器

How to Template a Bitshifter

我正在尝试创建一个用于初始化

的移位器

我正在尝试创建一个模板,允许用户定义要移位的内容。此处定义的其他 classes 仅允许用户从输入读取并写入输出,示例如下所示:

我开始写的移位器看起来像这样,虽然我有点卡住了,只需要一些想法让我重新开始

  template<typename T >
    class Bitshifter :
    {
        public:
          Bitshifter(T val) : memory_(val)
        {
        }

        ~Bitshifter() {}

        virtual void Tick( T input)
        {
              std::cout << (memory_ << 1 | input) << std::endl;
        }

    private:
            T memory_;
    };
}


Bitshifter<uint32_t> myComponent<0>;
myComponent.Tick(1);//
myComponent.Tick(0);//

所以它应该产生:

0x1
0x2

如果能够使用一些不同的类型,例如:

std::bitset<N>uint64_t

但如果可能的话,我还想使用我在 class 中定义的值,例如:

template<size_t N>
class std_logic_vector
{
public:
  typedef std::bitset<N> std_logic_vector_t;


public:
  std_logic_vector() :
    std_logic_vector_ (0)
  {}

  std_logic_vector(
           std_logic_vector_t value
           ):
std_logic_vector_ (value)
  {}

  ~std_logic_vector(){}

  std_logic_vector_t value() const {return std_logic_vector_;}

private:
  std_logic_vector_t std_logic_vector_;
};

然后我可以使用:

Bitset<std_logic_vector<32>>(std_logic_vector<32>())

但是在尝试进行位移操作时失败了。

您的示例代码几乎已经完全符合您的要求。 我稍微调整了一下,加了一些例子。

#include <memory>
#include <iostream>
#include <bitset>
#include <iomanip>

template<typename T >
class Bitshifter
{
public:
    Bitshifter(T val) 
        :memory_(val)
    {
    }

    ~Bitshifter() {}

    virtual void Tick(T input)
    {
        memory_ <<= 1;
        memory_ |= input;
        std::cout << "0x" << std::hex << memory_ << std::endl;
    }

private:
    T memory_;
};


int main()
{
    Bitshifter<uint32_t> myComponent1(0);
    myComponent1.Tick(1);//
    myComponent1.Tick(0);//

    Bitshifter<uint64_t> myComponent2(0);
    myComponent2.Tick(1);//
    myComponent2.Tick(0);//

    Bitshifter<std::bitset<10>> myComponent3(0x01);
    myComponent3.Tick(0x01);
    myComponent3.Tick(0x00);


}

输出:

0x1
0x2
0x1
0x2
0x0000000011
0x0000000110