推 ric2k1:推! 感謝分享! 12/28 22:19
其實這個叫作 unspecified_bool,有很多種其怪的寫法,光是 BOOST
函式庫就有三種。我覺得還頗有趣的。不過這種東西好像是在幫編譯
器出考題一樣。
簡單版: cast to void const *
class Even
{
int i;
public:
Even(int i_) : i(i_) {}
operator void const * () const { return (i % 2 == 0) ? this : 0 ; }
};
進階版: cast to member selector
class Even
{
int i;
typedef int (Even::*member_selector);
public:
Even(int i_) : i(i_) {}
operator member_selector () const { return (i % 2 == 0) ? &Even::i : 0 ; }
};
高階版: cast to member function selector
class Even
{
int i;
typedef int (Even::*unspecified_bool_t)() const;
public:
Even(int i_) : i(i_) {}
int get() const { return i; }
operator unspecified_bool_t () const
{
return (i % 2 == 0) ? &Even::get : 0 ;
}
};
非常強大版: cast to static member function selector
class Even
{
int i;
private:
static void unspecified_bool(Even ***) {}
typedef void (*unspecified_bool_t)(Even ***);
public:
Even(int i_) : i(i_) {}
operator unspecified_bool_t ()
{
return (i % 2 == 0) ? unspecified_bool : 0;
}
};
ref. Boost SmartPtr Lib http://tinyurl.com/yh5vh8r
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.247.159