Home > database >  Is there a way to optimize/reduce this sequence of assigning variables? (C )
Is there a way to optimize/reduce this sequence of assigning variables? (C )

Time:10-03

I was wondering if there's a way to optimize/reduce this logic? As the number of the variables increases, the number of the parameters increases as well, which can make the code a bit messy.

.h file

class ClassA
{
public:
    ClassB type1_1;
    ClassB type1_2;
    ClassB type1_3;
    // ... There can be more than this

    ClassB type2_1;
    ClassB type2_2;
    ClassB type2_3;
    // ... There can be more than this

    void SetType1(ClassB a, ClassB b, ClassB c);
    void SetType2(ClassB a, ClassB b, ClassB c);

    __forceinline vector<ClassB> GetListofType1() { return list_type1; }
    __forceinline vector<ClassB> GetListofType2() { return list_type2; }

private:
    vector<ClassB> list_type1;
    vector<ClassB> list_type2;
};

.cpp file

// ... As the number of type1 variables increases, the number of parameters increases
void ClassA::SetType1(ClassB a, ClassB b, ClassB c)
{
    type1_1 = a;
    type1_2 = b;
    type1_3 = c;

    list_type1.push_back(a);
    list_type1.push_back(b);
    list_type1.push_back(c);
}

// ... As the number of type2 variables increases, the number of parameters increases
void ClassA::SetType2(ClassB a, ClassB b, ClassB c)
{
    type2_1 = a;
    type2_2 = b;
    type2_3 = c;

    list_type2.push_back(a);
    list_type2.push_back(b);
    list_type2.push_back(c);
}

CodePudding user response:

Use initializer lists:

#include <cassert>
#include <vector>

struct ClassB { };

class ClassA {
public:
  static constexpr int list_type1_len = 3;

  inline void SetType1(const std::vector<ClassB>& set_type_1){
      assert(set_type_1.size()==3);
      list_type1 = set_type_1;
  }

  inline std::vector<ClassB>& GetListofType1() { return list_type1; }

private:
  std::vector<ClassB> list_type1;
};


int main(){
    ClassA a;
    a.SetType1({ClassB(), ClassB(), ClassB()});

    return 0;
}

CodePudding user response:

If the number of elements is known at compile time, you may be able to solve your code duplication problem using variadic templates and tuples or arrays.

For example:

#include <iostream>
#include <array>

template <typename T, unsigned N1, unsigned N2>
class ClassA {
public:
  std::array<std::array<T,N2>,N1> xs { };

  template <unsigned N, typename... X>
  void SetType(X&&... x) {
    std::get<N>(xs) = { std::forward<X>(x)... };
  }

  template <unsigned I1, unsigned I2>
  T& get() {
    return std::get<I2>(std::get<I1>(xs));
  }
};

int main(int argc, char* argv[]) {
  ClassA<int,2,3> a;

  a.SetType<0>(1,2,3);

  std::cout << a.get<0,1>() << std::endl;
}
  • Related