为此,在我的程序中,我想为IPAddressV4定义一个新的数据类型,我定义了以下类:
#include <boost/array.hpp>
#include <boost/asio.hpp>
#include "archive.hpp"
using boost::asio::ip::address_v4;
typedef boost::uint8_t uint8; /**< 8-bit unsigned interger. */
class IPAddrV4
{
public:
/**
* Construct a IPAddrV4 data type.
*/
IPAddrV4() : _ip_address(0)
{}
/**
* Construct a IPAddrV4 data type.
*
* @param ip_address The value of the IPv4 Address in text format.
*/
IPAddrV4(std::string ip_address) : _ip_address(0)
{
*this = ip_address;
}
/**
* Set the IPv4 Address value.
*
* @param val The value of the IPv4 Address in text format.
* @return The reference to the IPAddrV4 data type.
*/
IPAddrV4& operator=(std::string ip_address)
{
boost::asio::ip::address_v4::bytes_type bytes
= boost::asio::ip::address_v4::from_string(ip_address).to_bytes();
_ip_address = ((uint32(bytes.at(0)) << 24) |
(uint32(bytes.at(1)) << 16) |
(uint32(bytes.at(2)) << 8) |
uint32(bytes.at(3)));
return *this;
}
IPAddrV4& operator=(uint32 ip_address)
{
_ip_address = ip_address;
return *this;
}
/**
* Get the IPv4 Address data type value.
*
* @return The IPv4 Address data type value in binary form.
*/
operator uint32()
{
return _ip_address;
}
private:
uint32 _ip_address;
};
稍后,我将使用此类进行一些序列化和反序列化,以通过TCP连接发送数据。
当我使用输出文件进行序列化时,我没有任何问题。
IPAddrV4 ip("127.0.0.1");
oarchive & ip;
在上面的示例中,IP的值转换为二进制形式,然后复制到输出文件中。归档文件的大小将增加4个字节。
但是,当我尝试使用此数据类型与输入文件进行序列化时,我遇到了问题:
IPAddrV4 ip;
iarchive & ip;
这是我在编译时遇到的错误:
No match for 'operator&' in 'input_Archive & IPAddrV4::operator uint32()'
那我在IPAddrV4中缺少什么呢?
注意:输入存档与标准c++数据类型(例如uint,string..etc)完美配合。
最佳答案
Boost序列化为此具有BOOST_STRONG_TYPEDEF
。
也可以看看
关于c++ - 定义行为类似于标准c++数据类型的新数据类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23462329/