居家隔离中在github上找代码看着玩,偶然看到switch和nds的ftp服务代码,其中我发现那波日本人好像很喜欢重载隐式转换,然后顺手写一个笔记。
先引入一点点ftpd的代码:
namespace fs
{
/// \brief File I/O object
class File
{
public:
/// \brief bool cast operator
explicit operator bool () const {
return static_cast<bool> (m_fp);
}
/// \brief std::FILE* cast operator
operator std::FILE * () const {
return m_fp.get ();
}
...
private:
/// \brief Underlying std::FILE*
std::unique_ptr<std::FILE, int (*) (std::FILE *)> m_fp{nullptr, nullptr};
...
};
class SockAddr
{
public:
/// \param sockaddr_in cast operator
operator struct sockaddr_in const & () const {
assert (m_addr.ss_family == AF_INET);
return reinterpret_cast<struct sockaddr_in const &> (m_addr);
}
/// \param sockaddr_storage cast operator
operator struct sockaddr_storage const & () const;
/// \param sockaddr* cast operator
operator struct sockaddr * ();
/// \param sockaddr const* cast operator
operator struct sockaddr const * () const;
...
private:
/// \brief Address storage
struct sockaddr_storage m_addr = {};
};
用int operator()
和operator int()
举例
int operator()
是一个函数调用运算符,它将对象转换为可以像函数一样调用的函数对象。返回int。
例如:
struct Struct1 {
int operator()(int a, int b) { return a + b; }
};
...
Struct1 param;
int i = param(1, 2); // Call the object as a function, and it returns 3 (1+2)
operator int()
是转换运算符。这个特定的类型允许对象隐式(如果声明为显式,则显式)转换为int。它必须返回int(或者无论使用什么类型,也可以使用用户定义的类型,如类或结构)。
例如:
struct Struct2 {
operator int() { return 666; }
};
...
Struct2 param;
int i = param; // Calls the conversion operator, which returns 666