What is the most efficient way to represent small values in a struct?

前端 未结 15 847
星月不相逢
星月不相逢 2021-02-01 02:15

Often I find myself having to represent a structure that consists of very small values. For example, Foo has 4 values, a, b, c, d that, range from

15条回答
  •  南方客
    南方客 (楼主)
    2021-02-01 03:04

    I think the only real answer can be to write your code generically, and then profile the full program with all of them. I don't think this will take that much time, though it may look a little more awkward. Basically, I'd do something like this:

    template  class Foo;
    using interface_int = char;
    
    template <>
    class Foo {
        char m_a, m_b, m_c, m_d;
     public: 
        void setA(interface_int a) { m_a = a; }
        interface_int getA() { return m_a; }
        ...
    }
    
    template <>
    class Foo {
      char m_data;
     public:
        void setA(interface_int a) { // bit magic changes m_data; }
        interface_int getA() { // bit magic gets a from m_data; }
    }
    

    If you just write your code like this instead of exposing the raw data, it will be easy to switch implementations and profile. The function calls will get inlined and will not impact performance. Note that I just wrote setA and getA instead of a function that returns a reference, this is more complicated to implement.

提交回复
热议问题