![](/img/trans.png)
[英]How to call 'call by value ' and 'call by reference' overloaded function?
[英]How to call overloaded function using return value from other function
我具有以下類層次結構:
Option (abstract) ^ | +------+-------+ | | + + Something[T] Nothing
實現如下:
class Option {
public:
Option() {};
virtual ~Option() {};
virtual bool nothing() = 0;
};
template <typename T>
class Something : public Option
{
public:
Something(T _value) : value(_value) {};
virtual ~Something() {};
const T value;
virtual bool nothing() {return false;};
};
class Nothing : public Option
{
public:
Nothing() {};
virtual ~Nothing() {};
virtual bool nothing() {return true;};
};
現在,我希望能夠編寫具有以下簽名的函數:
is_nothing: Nothing& => True
is_nothing: Something[T]& => False
我嘗試以以下方式使用模板:
template <class T> bool is_nothing(Nothing&) {return true;};
template <class T> bool is_nothing(Something<T> &) {return false;};
當這樣使用時它確實起作用:
is_nothing<int>(Nothing());
is_nothing<int>(Something<int>(4));
但由於缺少is_nothing: Option& => bool
而不想編譯is_nothing: Option& => bool
像這樣is_nothing<int>(an_option())
, an_option: void => Option&
is_nothing: Option& => bool
,其中an_option: void => Option&
實際上返回Nothing
的實例。 因此對我來說,它似乎突然失去了進行多態調用的能力。
使用Option
代碼:
Nothing n;
Option& an_option() {return n;};
int main(int argc,char** argv)
{
is_nothing<int>(an_option());
return 0;
}
請引導我朝正確的方向前進,因為我認為這種方法有誤,但我不能完全按此說。
重載解析是根據參數的靜態類型而不是動態 (運行時)類型完成的。 當您調用is_nothing<int>(an_option())
,編譯器將an_option()
解析為返回Option&
的函數,並將嘗試根據該類型而不是引用綁定的對象的類型進行解析。
如果您解釋了要解決的問題,則可能會得到一些在該語言范圍內可行的替代設計。 最簡單,通用的方法是使用RTTI信息來推斷實際類型,但同時又被認為是代碼異味,我不建議這樣做。 特別是, is_nothing
的實現可以引用Option
並使用RTTI( dynamic_cast
或typeid
)確定對象的動態類型是什么,並采取相應的措施。
但是,這是一個糟糕的設計,如果您在什么情況下解釋您需要它以及您真正想解決什么,您將獲得更好的選擇。
您不需要兩個單獨的功能。 Option
具有一個虛擬的nothing()
方法,因此您可以創建一個非模板函數,該函數返回nothing()
返回的內容:
bool is_nothing(Option& opt) { return opt.nothing(); }
Nothing n;
Option& an_option() { return n; }
int main(int argc,char** argv)
{
if (is_nothing(an_option()))
...
return 0;
}
當您可以直接調用nothing()
時,這當然是多余的:
Nothing n;
Option& an_option() { return n; }
int main(int argc,char** argv)
{
if (an_option().nothing())
...
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.