admin管理员组

文章数量:1320888

The code below errors when writing BOOST_CLASS_EXPORT(DerivedA<double, float>). However, by defining an alias using alias = DerivedA<double, float>; BOOST_CLASS_EXPORT(alias); the code works. Is there a cleaner solution without type aliases when using the BOOST_CLASS_EXPORT macro for structs/classes with templates?

The error message is

error: macro "BOOST_CLASS_EXPORT" passed 2 arguments, but takes just 1
   35 | BOOST_CLASS_EXPORT(DerivedA<double, float>) // ERROR
      |                                           ^
In file included from /opt/boost-1.79.0-r7de4sm2snkkg5mu5iamq2vdfpwrloi4/include/boost/serialization/export.hpp:215: note: macro "BOOST_CLASS_EXPORT" defined here
  215 | #define BOOST_CLASS_EXPORT(T)                   \
      | 
/home/test/main:35:1: error: ‘BOOST_CLASS_EXPORT’ does not name a type
   35 | BOOST_CLASS_EXPORT(DerivedA<double, float>) // ERROR
      | ^~~~~~~~~~~~~~~~~~

Code

#include <iostream>
#include <memory>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/export.hpp>

// Base class
template<typename T, typename U>
class Base {
public:
    virtual ~Base() = default;

    template<class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        // No members to serialize
    }
};

template<typename T, typename U>
class DerivedA : public Base<T, U> {
public:
    T valueA;
    U valueB;

    DerivedA() = default;

    template<class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        ar & boost::serialization::base_object<Base<T, U>>(*this);
        ar & valueA;
        ar & valueB;
    }
};
BOOST_CLASS_EXPORT(DerivedA<double, float>) // ERROR
// using alias = DerivedA<double, float>;
// BOOST_CLASS_EXPORT(alias); // WORKS


// Struct holding a shared_ptr to Base
template<typename T, typename U>
struct MyStruct {
    std::shared_ptr<Base<T, U>> ptr;

    template<class Archive>
    void serialize(Archive& ar, const unsigned int version) {
        ar &ptr; 
    }
};

int main() {

    MyStruct<double, float> original;
    original.ptr = std::make_shared<DerivedA<double, float>>(); // Store DerivedA

    return 0;
}

本文标签: c boost class export with templatesStack Overflow