gpt4 book ai didi

c++ - 两种专门方法中的相同代码

转载 作者:行者123 更新时间:2023-11-30 05:11:09 25 4
gpt4 key购买 nike

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

// 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. 有没有更好的方法来做我想做的事?

最佳答案

做到这一点的最简单方法是只拥有一个这两个调用的实现方法

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);
}

关于c++ - 两种专门方法中的相同代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45243306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com