我想知道是否有一种方法来优化/减少这个逻辑?随着变量数量的增加,参数的数量也会增加,这会使代码变得有点混乱。
. h文件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文件// ... 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);
}
使用初始化器列表:
#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;
}
如果在编译时知道元素的数量,您可以使用可变模板和tuple
s或array
s来解决代码重复问题。
例如:
#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;
}