将临时序列化为 boost 存档

serialize temporary into boost archive

任何提升输出存档都不可能:

int foo(){
   return 4;
}

ar << static_cast<unsigned int>(foo());

有没有不创建本地临时文件的替代方案x=foo()

为什么底层存档 operator <<(T & t) 不是 const reference ,对于输出存档,上面的内容可以工作?

这似乎可行,我认为 this 是原因:

... To help detect such cases, output archive operators expect to be passed const reference arguments.

似乎值得注意的是,在您的示例中 ar << foo(); 也不起作用(即它与您的演员表无关)。

#include <fstream>
#include <iostream>

#include <boost/serialization/serialization.hpp>
#include <boost/archive/text_iarchive.hpp>
#include <boost/archive/text_oarchive.hpp>

unsigned int foo(){
   return 4;
}

int main()
{
    {
    std::ofstream outputStream("someFile.txt");
    boost::archive::text_oarchive outputArchive(outputStream);
    outputArchive << static_cast<const int&>(foo());
    }

    std::ifstream inputStream("someFile.txt");
    boost::archive::text_iarchive inputArchive(inputStream);

    int readBack;
    inputArchive >> readBack;

    std::cout << "Read back: " << readBack << std::endl;
    return 0;
}