将类似的功能代码组合到模板中

时间:2012-11-05 08:56:47

标签: c++ templates

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

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 ++技巧,最好是模板技巧,以减少这种类型代码的单一调用。

1 个答案:

答案 0 :(得分: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()
}