다른 유형의 데이터 멤버가 많은 클래스가 있고 나중에 추가 할 수 있다고 가정합니다.
Class A
{
public:
int getA();
void setA(int a);
...
private:
int m_a;
int m_b;
double m_c;
string m_d;
CustomerType m_e;
char * m_f;
...
}
문제는 다른 데이터 멤버를 추가 할 때마다 get / set 함수를 추가해야한다는 것입니다. 어떤 이유로 나는 그들을 공개로 변경할 수 없습니다.
한 가지 해결책은 템플릿과 함께 getType / setType 함수를 사용하는 것입니다.
Class A
{
public:
int getInt(int id){
switch(id)
case ID_A:
return m_a;
case ID_B:
return m_b;
...
}
void setInt(int id,int i){...}
double getDouble(){...}
void setDouble(int id,double d){...}
...
template<T>
T get();
template<> //specialize
double get<double>(){return getDouble();}
...
private:
}
더 나은 해결책이 있습니까? 감사.
저에게 맞는 전략이 있습니다.
#include <string>
struct CustomerType {};
class A
{
public:
template <typename T> struct member
{
typedef T type;
type data;
};
struct type_A : member<int> {};
struct type_B : member<int> {};
struct type_C : member<double> {};
struct type_D : member<std::string> {};
struct type_E : member<CustomerType> {};
struct type_F : member<char*> {};
template <typename T>
typename T::type get()
{
return ((T&)allData).data;
}
template <typename T>
void set(typename T::type d)
{
((T&)allData).data = d;
}
private:
struct AllData : type_A,
type_B,
type_C,
type_D,
type_E,
type_F {};
AllData allData;
};
int main()
{
A a;
a.set<A::type_A>(20);
int b = a.get<A::type_A>();
return 0;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다