两种专业方法中的相同代码

时间:2017-07-21 17:19:26

标签: c++ dry template-specialization boost-serialization

我有一个带有空模板方法的类:

// my method in a class
template<class U>
void save(U& archive, const unsigned int version) const {
    // empty
}

我在同一个标​​题中的类之后有三个sepcializations,但其中两个具有相同的代码:

template<>
void Dataset1::save(boost::archive::xml_oarchive& archive, const unsigned int version) const {
    archive & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Dataset0);
    archive & BOOST_SERIALIZATION_NVP(m_a1_);
    archive & BOOST_SERIALIZATION_NVP(m_b1_);
}

template<>
void Dataset1::save(boost::archive::text_oarchive& archive, const unsigned int version) const {
    archive & boost::serialization::base_object<Dataset0>(*this);
    archive & m_a1_;
    archive & m_b1_;
}

template<>
void Dataset1::save(boost::archive::binary_oarchive& archive, const unsigned int version) const {
    archive & boost::serialization::base_object<Dataset0>(*this);
    archive & m_a1_;
    archive & m_b1_;
}
  1. 我可以做些什么来不重复自己?
  2. 是否可以使用空方法?
  3. 有没有更好的方法来做我想做的事情?

1 个答案:

答案 0 :(得分:1)

最简单的方法是只使用这两个调用的实现方法

class Dataset1 {

    ... 

private:
    template <typename T>
    void save_impl_text_binary(T& archive, const unsigned int version) const {
        archive & boost::serialization::base_object<Dataset0>(*this);
        archive & m_a1_;
        archive & m_b1_;
    }
};

template<>
void Dataset1::save(boost::archive::xml_oarchive& archive, const unsigned int version) const {
    archive & BOOST_SERIALIZATION_BASE_OBJECT_NVP(Dataset0);
    archive & BOOST_SERIALIZATION_NVP(m_a1_);
    archive & BOOST_SERIALIZATION_NVP(m_b1_);
}

template<>
void Dataset1::save(boost::archive::text_oarchive& archive, const unsigned int version) const {
    this->save_impl_text_binary(archive, version);
}

template<>
void Dataset1::save(boost::archive::binary_oarchive& archive, const unsigned int version) const {
    this->save_impl_text_binary(archive, version);
}