1

我必须编写以下类型的代码

if ( itr->second == "char" ) 
{
    MemberProperty<Owner,char> *ptr = (MemberProperty<Owner, char> *)GetterSetterItr->second;
    pw->writeChar(itr->first.c_str() ,(pOwner->*(ptr->m_Getter))());
} else if ( itr->second == "wchar" ) {
   MemberProperty<Owner,wchar_t> *ptr = (MemberProperty<Owner, wchar_t> *)GetterSetterItr->second;
   pw->writeWideChar(itr->first.c_str() ,(pOwner->*(ptr->m_Getter))());
}

会有很多类型,是否有任何 c++ 技巧,最好是模板技巧,以将其减少到对此类代码的一次调用。

4

1 回答 1

0

假设 writeChar() 和 writeWideChar() 除了参数类型之外是相同的,您可以像这样重构代码:

if (it->second == "char")
  pw->writeChar<char>(itr->first, GetterSetterItr->second);
else if (itr->second == "wchar")
  pw->writeChar<wchar_t>(itr->first, GetterSetterItr->second);

然后在 *pw 为实例的类中,将 writeChar 和 writeWideChar 替换为模板成员函数:

template <typename CharType>
void writeChar(std::string str, /*the type of GetterSetterItr->second*/ arg) {
  MemberProperty<Owner, CharType> *ptr = (MemberProperty<Owner, CharType>*)arg;
  // the rest of code of old writeChar() and writeWideChar()
}
于 2012-11-05T09:08:44.517 回答