全部。我對C++相當陌生,並且正在用C++編寫一個小型庫(主要用於我自己的項目)。在設計類型層次結構的過程中,我遇到了定義賦值運算符的問題。編譯時的C++類型檢查
我所採取的最終在this article達到的基本方法,這是一個爲每個類MyClass
在層次結構從類派生Base
定義就像兩個賦值運算符這樣:
class MyClass: public Base {
public:
MyClass& operator =(MyClass const& rhs);
virtual MyClass& operator =(Base const& rhs);
};
// automatically gets defined, so we make it call the virtual function below
MyClass& MyClass::operator =(MyClass const& rhs);
{
return (*this = static_cast<Base const&>(rhs));
}
MyClass& MyClass::operator =(Base const& rhs);
{
assert(typeid(rhs) == typeid(*this)); // assigning to different types is a logical error
MyClass const& casted_rhs = dynamic_cast<MyClass const&>(rhs);
try {
// allocate new variables
Base::operator =(rhs);
} catch(...) {
// delete the allocated variables
throw;
}
// assign to member variables
}
的一部分我關心的是類型平等的斷言。由於我正在寫一個圖書館,斷言大概會被編出來的最終結果,這導致我去同一個方案,它看起來更像是這樣的:
class MyClass: public Base {
public:
operator =(MyClass const& rhs); // etc
virtual inline MyClass& operator =(Base const& rhs)
{
assert(typeid(rhs) == typeid(*this));
return this->set(static_cast<Base const&>(rhs));
}
private:
MyClass& set(Base const& rhs); // same basic thing
};
但我一直在想,如果我可以在編譯時檢查類型。我看着Boost.TypeTraits,並且通過做BOOST_MPL_ASSERT((boost::is_same<BOOST_TYPEOF(*this), BOOST_TYPEOF(rhs)>));
來接近,但是由於rhs被聲明爲對父類而不是派生類的引用,所以它被阻塞了。
現在我想到了,我的推理看起來很愚蠢 - 我希望既然函數是內聯的,它可以自己檢查實際參數,但是當然預處理器總是在編譯器之前運行。但是我想知道是否有人知道我可以在編譯時執行這種檢查。
沒有辦法在編譯時檢查類型,因爲這是多態性的要點:事物的類型只在運行時確定。 '動物*動物=蘭特()%2?新的狗():新的貓();' – UncleBens 2010-04-12 07:02:42
好文章鏈接的方式,謝謝:) – 2010-04-12 09:14:38