fiz
fiz

Reputation: 936

How to Template a Bitshifter

I'm trying to create a bitshifter which initialises

I'm trying to create a template that allows the user to define something to bitshift. The other classes defined here just allow the user to read from an input and write to an output, an example looks like this:

The bitshifter I've started writing looks like this though I'm a little stuck and just need a few ideas to get me going again

  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);//

So it should produce:

0x1
0x2

It would be quite nice to be able to use a few different types such as:

std::bitset<N> and uint64_t

But I'd also like to use values if possible that I have defined in a class such as:

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_;
};

Then I could use:

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

But it fails when trying to do the bitshift operation.

Upvotes: 1

Views: 91

Answers (1)

Simon Kraemer
Simon Kraemer

Reputation: 5680

Your example code pretty much already does exactly what you want. I adjusted it a little bit and added some examples.

#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);


}

Output:

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

Upvotes: 1

Related Questions